Skip to content

Commit

Permalink
CreateProjectMojo - validate className
Browse files Browse the repository at this point in the history
  • Loading branch information
rsvoboda committed Feb 1, 2020
1 parent cdb9a1d commit 7cfb0d9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.util.Set;
import java.util.stream.Collectors;

import javax.lang.model.SourceVersion;

import org.apache.commons.lang3.StringUtils;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionRequest;
Expand Down Expand Up @@ -192,6 +194,10 @@ public void execute() throws MojoExecutionException {
final SourceType sourceType = CreateProject.determineSourceType(extensions);
sanitizeOptions(sourceType);

if (className != null && !isClassNameValid(className)) {
throw new MojoExecutionException("Unable to create the project, " + className + " is not valid FQCN.");
}

final Map<String, Object> context = new HashMap<>();
context.put("path", path);

Expand Down Expand Up @@ -383,6 +389,10 @@ private void sanitizeOptions(SourceType sourceType) {
}
}

private boolean isClassNameValid(String className) {
return SourceVersion.isName(className) && !SourceVersion.isKeyword(className);
}

private void sanitizeExtensions() {
extensions = extensions.stream().filter(Objects::nonNull).map(String::trim).collect(Collectors.toSet());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,23 @@ public void testProjectGenerationFromScratchWithResource() throws Exception {
check(new File(testDir, "src/main/java/org/acme/MyResource.java"), "package org.acme;");
}

@Test
public void testProjectGenerationWithInvalidPackage() throws Exception {
testDir = initEmptyProject("projects/project-generation-invalid-package");
assertThat(testDir).isDirectory();
invoker = initInvoker(testDir);

Properties properties = new Properties();
properties.put("projectGroupId", "org.acme");
properties.put("projectArtifactId", "acme");
properties.put("className", "org.acme.invalid-package-name.MyResource");

InvocationResult result = setup(properties);

assertThat(result.getExitCode()).isNotZero();
assertThat(new File(testDir, "src/main/java/org/acme")).doesNotExist();
}

@Test
public void testProjectGenerationFromMinimalPomWithResource() throws Exception {
testDir = initProject("projects/simple-pom-it", "projects/project-generation-from-empty-pom-with-resource");
Expand Down

0 comments on commit 7cfb0d9

Please sign in to comment.