diff --git a/README.md b/README.md index 78ab304..ee7fdb7 100644 --- a/README.md +++ b/README.md @@ -21,3 +21,4 @@ For publishing the site do the following: cd target/checkout mvn verify site site:stage scm-publish:publish-scm ``` + diff --git a/pom.xml b/pom.xml index 8cc95dc..91b1e67 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 org.codehaus.mojo mojo-parent - 78 + 82 templating-maven-plugin @@ -33,12 +31,10 @@ maven-plugin - https://www.mojohaus.org/templating-maven-plugin - Templating Maven Plugin - - That project was designed to offer the Maven Right Way® :-) to filter sources. - + That project was designed to offer the Maven Right Way® :-) to filter sources. + + https://www.mojohaus.org/templating-maven-plugin 2013 @@ -52,18 +48,18 @@ Karl Heinz Marbaise - +1 khmarbaise@apache.org Developer + +1 Baptiste Mathus - +1 Developer + +1 Stephen Connolly @@ -90,8 +86,8 @@ scm:git:https://github.com/mojohaus/templating-maven-plugin.git scm:git:ssh://git@github.com/mojohaus/templating-maven-plugin.git - https://github.com/mojohaus/templating-maven-plugin 3.0.0 + https://github.com/mojohaus/templating-maven-plugin @@ -108,15 +104,6 @@ target/staging/${project.artifactId} - - - - org.apache.maven.plugins - maven-plugin-plugin - - - - org.apache.maven @@ -175,6 +162,15 @@ + + + + org.apache.maven.plugins + maven-plugin-plugin + + + + diff --git a/src/main/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojo.java b/src/main/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojo.java index 7fe27f8..01ae419 100644 --- a/src/main/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojo.java +++ b/src/main/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojo.java @@ -45,9 +45,7 @@ /** * The base class for {@link FilterSourcesMojo} and {@link FilterTestSourcesMojo} */ -public abstract class AbstractFilterSourcesMojo - extends AbstractMojo -{ +public abstract class AbstractFilterSourcesMojo extends AbstractMojo { private static final int CHECKSUM_BUFFER = 4096; private int copied = 0; @@ -65,13 +63,13 @@ public abstract class AbstractFilterSourcesMojo /** * The character encoding scheme to be applied when filtering resources. */ - @Parameter( defaultValue = "${project.build.sourceEncoding}" ) + @Parameter(defaultValue = "${project.build.sourceEncoding}") private String encoding; /** * Expression preceded with the String won't be interpolated \${foo} will be replaced with ${foo} */ - @Parameter( property = "maven.resources.escapeString" ) + @Parameter(property = "maven.resources.escapeString") protected String escapeString; /** @@ -95,337 +93,275 @@ public abstract class AbstractFilterSourcesMojo * Controls whether the default delimiters are included in addition to those configured {@link #delimiters}. Does * not have any effect if {@link #delimiters} is empty when the defaults will be included anyway. */ - @Parameter( defaultValue = "true" ) + @Parameter(defaultValue = "true") protected boolean useDefaultDelimiters; - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) private MavenSession session; - @Parameter( defaultValue = "${project}", required = true, readonly = true ) + @Parameter(defaultValue = "${project}", required = true, readonly = true) private MavenProject project; /** * Controls whether to overwrite files that are not changed, by default files will not be overwritten */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") protected boolean overwrite; /** * Skips POM projects if set to true, which is the default option. */ - @Parameter( defaultValue = "true" ) + @Parameter(defaultValue = "true") protected boolean skipPoms; /** * The resources filtering which is used. */ - @Component( hint = "default" ) + @Component(hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** {@inheritDoc} */ @Override - public void execute() - throws MojoExecutionException - { + public void execute() throws MojoExecutionException { File sourceDirectory = getSourceDirectory(); - if ( !preconditionsFulfilled( sourceDirectory ) ) - { + if (!preconditionsFulfilled(sourceDirectory)) { return; } // 1 Copy with filtering the given source to temporary dir copied = 0; - File temporaryDirectory = getTemporaryDirectory( sourceDirectory ); - logInfo( "Copying files with filtering to temporary directory." ); - logDebug( "Temporary directory for filtering is: %s", temporaryDirectory ); - filterSourceToTemporaryDir( sourceDirectory, temporaryDirectory ); + File temporaryDirectory = getTemporaryDirectory(sourceDirectory); + logInfo("Copying files with filtering to temporary directory."); + logDebug("Temporary directory for filtering is: %s", temporaryDirectory); + filterSourceToTemporaryDir(sourceDirectory, temporaryDirectory); // 2 Copy if needed - copyDirectoryStructure( temporaryDirectory, getOutputDirectory() ); - cleanupTemporaryDirectory( temporaryDirectory ); - if ( isSomethingBeenUpdated() ) - { - logInfo( "Copied %d files to output directory: %s", copied, getOutputDirectory() ); - } - else - { - logInfo( "No files need to be copied to output directory. Up to date: %s", getOutputDirectory() ); + copyDirectoryStructure(temporaryDirectory, getOutputDirectory()); + cleanupTemporaryDirectory(temporaryDirectory); + if (isSomethingBeenUpdated()) { + logInfo("Copied %d files to output directory: %s", copied, getOutputDirectory()); + } else { + logInfo("No files need to be copied to output directory. Up to date: %s", getOutputDirectory()); } // 3 Add that dir to sources - addSourceFolderToProject( this.project ); - logInfo( "Source directory: %s added.", getOutputDirectory() ); + addSourceFolderToProject(this.project); + logInfo("Source directory: %s added.", getOutputDirectory()); } /** * @return number of copied files. */ - protected int countCopiedFiles() - { + protected int countCopiedFiles() { return copied; } - private void logInfo( String format, Object... args ) - { - if ( getLog().isInfoEnabled() ) - { - getLog().info( String.format( format, args ) ); + private void logInfo(String format, Object... args) { + if (getLog().isInfoEnabled()) { + getLog().info(String.format(format, args)); } } - private void logDebug( String format, Object... args ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( String.format( format, args ) ); + private void logDebug(String format, Object... args) { + if (getLog().isDebugEnabled()) { + getLog().debug(String.format(format, args)); } } - private boolean isSomethingBeenUpdated() - { + private boolean isSomethingBeenUpdated() { return copied > 0; } - private void cleanupTemporaryDirectory( File temporaryDirectory ) - throws MojoExecutionException - { - try - { - FileUtils.forceDelete( temporaryDirectory ); - } - catch ( IOException ex ) - { - throw new MojoExecutionException( ex.getMessage(), ex ); + private void cleanupTemporaryDirectory(File temporaryDirectory) throws MojoExecutionException { + try { + FileUtils.forceDelete(temporaryDirectory); + } catch (IOException ex) { + throw new MojoExecutionException(ex.getMessage(), ex); } } - private void filterSourceToTemporaryDir( final File sourceDirectory, final File temporaryDirectory ) - throws MojoExecutionException - { + private void filterSourceToTemporaryDir(final File sourceDirectory, final File temporaryDirectory) + throws MojoExecutionException { List resources = new ArrayList<>(); Resource resource = new Resource(); - resource.setFiltering( true ); - logDebug( "Source absolute path: %s", sourceDirectory.getAbsolutePath() ); - resource.setDirectory( sourceDirectory.getAbsolutePath() ); - resources.add( resource ); - - MavenResourcesExecution mavenResourcesExecution = - new MavenResourcesExecution( resources, temporaryDirectory, project, encoding, - Collections.emptyList(), Collections.emptyList(), session ); - mavenResourcesExecution.setInjectProjectBuildFilters( true ); - mavenResourcesExecution.setEscapeString( escapeString ); - mavenResourcesExecution.setOverwrite( overwrite ); - setDelimitersForExecution( mavenResourcesExecution ); - try - { - mavenResourcesFiltering.filterResources( mavenResourcesExecution ); - } - catch ( MavenFilteringException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + resource.setFiltering(true); + logDebug("Source absolute path: %s", sourceDirectory.getAbsolutePath()); + resource.setDirectory(sourceDirectory.getAbsolutePath()); + resources.add(resource); + + MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution( + resources, + temporaryDirectory, + project, + encoding, + Collections.emptyList(), + Collections.emptyList(), + session); + mavenResourcesExecution.setInjectProjectBuildFilters(true); + mavenResourcesExecution.setEscapeString(escapeString); + mavenResourcesExecution.setOverwrite(overwrite); + setDelimitersForExecution(mavenResourcesExecution); + try { + mavenResourcesFiltering.filterResources(mavenResourcesExecution); + } catch (MavenFilteringException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void setDelimitersForExecution( MavenResourcesExecution mavenResourcesExecution ) - { + private void setDelimitersForExecution(MavenResourcesExecution mavenResourcesExecution) { // if these are NOT set, just use the defaults, which are '${*}' and '@'. - if ( delimiters != null && !delimiters.isEmpty() ) - { + if (delimiters != null && !delimiters.isEmpty()) { LinkedHashSet delims = new LinkedHashSet<>(); - if ( useDefaultDelimiters ) - { - delims.addAll( mavenResourcesExecution.getDelimiters() ); + if (useDefaultDelimiters) { + delims.addAll(mavenResourcesExecution.getDelimiters()); } - for ( String delim : delimiters ) - { - if ( delim == null ) - { + for (String delim : delimiters) { + if (delim == null) { // FIXME: ${filter:*} could also trigger this condition. Need a better long-term solution. - delims.add( "${*}" ); - } - else - { - delims.add( delim ); + delims.add("${*}"); + } else { + delims.add(delim); } } - mavenResourcesExecution.setDelimiters( delims ); + mavenResourcesExecution.setDelimiters(delims); } } - private void preconditionsCopyDirectoryStructure( final File sourceDirectory, final File destinationDirectory, - final File rootDestinationDirectory ) - throws IOException - { - if ( sourceDirectory == null ) - { - throw new IOException( "source directory can't be null." ); + private void preconditionsCopyDirectoryStructure( + final File sourceDirectory, final File destinationDirectory, final File rootDestinationDirectory) + throws IOException { + if (sourceDirectory == null) { + throw new IOException("source directory can't be null."); } - if ( destinationDirectory == null ) - { - throw new IOException( "destination directory can't be null." ); + if (destinationDirectory == null) { + throw new IOException("destination directory can't be null."); } - if ( sourceDirectory.equals( destinationDirectory ) ) - { - throw new IOException( "source and destination are the same directory." ); + if (sourceDirectory.equals(destinationDirectory)) { + throw new IOException("source and destination are the same directory."); } - if ( !sourceDirectory.exists() ) - { - throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." ); + if (!sourceDirectory.exists()) { + throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")."); } } - private void copyDirectoryStructure( final File sourceDirectory, final File destinationDirectory ) - throws MojoExecutionException - { - try - { + private void copyDirectoryStructure(final File sourceDirectory, final File destinationDirectory) + throws MojoExecutionException { + try { File target = destinationDirectory; - if ( !target.isAbsolute() ) - { - target = resolve( project.getBasedir(), destinationDirectory.getPath() ); + if (!target.isAbsolute()) { + target = resolve(project.getBasedir(), destinationDirectory.getPath()); } - copyDirectoryStructureWithIO( sourceDirectory, target, target ); - } - catch ( IOException ex ) - { - throw new MojoExecutionException( ex.getMessage(), ex ); + copyDirectoryStructureWithIO(sourceDirectory, target, target); + } catch (IOException ex) { + throw new MojoExecutionException(ex.getMessage(), ex); } } - private void copyDirectoryStructureWithIO( final File sourceDirectory, final File destinationDirectory, - final File rootDestinationDirectory ) - throws IOException - { - preconditionsCopyDirectoryStructure( sourceDirectory, destinationDirectory, rootDestinationDirectory ); + private void copyDirectoryStructureWithIO( + final File sourceDirectory, final File destinationDirectory, final File rootDestinationDirectory) + throws IOException { + preconditionsCopyDirectoryStructure(sourceDirectory, destinationDirectory, rootDestinationDirectory); File[] files = sourceDirectory.listFiles(); - if ( files == null ) - { + if (files == null) { return; } String sourcePath = sourceDirectory.getAbsolutePath(); - for ( File file : files ) - { - if ( file.equals( rootDestinationDirectory ) ) - { + for (File file : files) { + if (file.equals(rootDestinationDirectory)) { // We don't copy the destination directory in itself continue; } String dest = file.getAbsolutePath(); - dest = dest.substring( sourcePath.length() + 1 ); + dest = dest.substring(sourcePath.length() + 1); - File destination = new File( destinationDirectory, dest ); + File destination = new File(destinationDirectory, dest); - if ( file.isFile() ) - { + if (file.isFile()) { destination = destination.getParentFile(); - if ( isFileDifferent( file, destination ) ) - { + if (isFileDifferent(file, destination)) { copied++; - FileUtils.copyFileToDirectory( file, destination ); + FileUtils.copyFileToDirectory(file, destination); } - } - else if ( file.isDirectory() ) - { - if ( !destination.exists() && !destination.mkdirs() ) - { - throw new IOException( "Could not create destination directory '" + destination.getAbsolutePath() - + "'." ); + } else if (file.isDirectory()) { + if (!destination.exists() && !destination.mkdirs()) { + throw new IOException( + "Could not create destination directory '" + destination.getAbsolutePath() + "'."); } - copyDirectoryStructureWithIO( file, destination, rootDestinationDirectory ); - } - else - { - throw new IOException( "Unknown file type: " + file.getAbsolutePath() ); + copyDirectoryStructureWithIO(file, destination, rootDestinationDirectory); + } else { + throw new IOException("Unknown file type: " + file.getAbsolutePath()); } } } - private File resolve( final File file, final String... subfile ) - { + private File resolve(final File file, final String... subfile) { StringBuilder path = new StringBuilder(); - path.append( file.getPath() ); - for ( String fi : subfile ) - { - path.append( File.separator ); - path.append( fi ); + path.append(file.getPath()); + for (String fi : subfile) { + path.append(File.separator); + path.append(fi); } - return new File( path.toString() ); + return new File(path.toString()); } - private boolean isFileDifferent( final File file, final File directory ) - throws IOException - { - File targetFile = resolve( directory, file.getName() ).getAbsoluteFile(); - return !targetFile.canRead() || getCrc32OfFile( file ) != getCrc32OfFile( targetFile ); + private boolean isFileDifferent(final File file, final File directory) throws IOException { + File targetFile = resolve(directory, file.getName()).getAbsoluteFile(); + return !targetFile.canRead() || getCrc32OfFile(file) != getCrc32OfFile(targetFile); } - private long getCrc32OfFile( final File target ) - throws IOException - { + private long getCrc32OfFile(final File target) throws IOException { FileInputStream fis = null; - try - { - fis = new FileInputStream( target ); + try { + fis = new FileInputStream(target); CRC32 crcMaker = new CRC32(); byte[] buffer = new byte[CHECKSUM_BUFFER]; int bytesRead; - while ( ( bytesRead = fis.read( buffer ) ) != -1 ) - { - crcMaker.update( buffer, 0, bytesRead ); + while ((bytesRead = fis.read(buffer)) != -1) { + crcMaker.update(buffer, 0, bytesRead); } return crcMaker.getValue(); - } - catch ( FileNotFoundException ex ) - { - close( fis ); - throw new IOException( ex.getLocalizedMessage(), ex ); - } - finally - { - close( fis ); + } catch (FileNotFoundException ex) { + close(fis); + throw new IOException(ex.getLocalizedMessage(), ex); + } finally { + close(fis); } } - private void close( Closeable is ) - throws IOException - { - if ( is != null ) - { + private void close(Closeable is) throws IOException { + if (is != null) { is.close(); } } - private File getTemporaryDirectory( File sourceDirectory ) { + private File getTemporaryDirectory(File sourceDirectory) { File basedir = project.getBasedir(); - File target = new File( project.getBuild().getDirectory() ); - StringBuilder label = new StringBuilder( "templates-tmp" ); + File target = new File(project.getBuild().getDirectory()); + StringBuilder label = new StringBuilder("templates-tmp"); CRC32 crcMaker = new CRC32(); - crcMaker.update( sourceDirectory.getPath().getBytes() ); - label.append( crcMaker.getValue() ); + crcMaker.update(sourceDirectory.getPath().getBytes()); + label.append(crcMaker.getValue()); String subfile = label.toString(); - return target.isAbsolute() ? resolve( target, subfile ) : resolve( basedir, target.getPath(), subfile ); + return target.isAbsolute() ? resolve(target, subfile) : resolve(basedir, target.getPath(), subfile); } - private boolean preconditionsFulfilled( File sourceDirectory ) - { - if ( skipPoms && "pom".equals( project.getPackaging() ) ) - { - logInfo( "Skipping POM project type. Change `skipPoms` to false to run anyway." ); + private boolean preconditionsFulfilled(File sourceDirectory) { + if (skipPoms && "pom".equals(project.getPackaging())) { + logInfo("Skipping POM project type. Change `skipPoms` to false to run anyway."); return false; } - logDebug( "source=%s target=%s", sourceDirectory, getOutputDirectory() ); - if ( !( sourceDirectory != null && sourceDirectory.exists() ) ) - { - logInfo( "Requested directory '%s' not added since it does not exist.", sourceDirectory ); + logDebug("source=%s target=%s", sourceDirectory, getOutputDirectory()); + if (!(sourceDirectory != null && sourceDirectory.exists())) { + logInfo("Requested directory '%s' not added since it does not exist.", sourceDirectory); return false; } return true; @@ -434,5 +370,5 @@ private boolean preconditionsFulfilled( File sourceDirectory ) /** * @param mavenProject {@link MavenProject} */ - protected abstract void addSourceFolderToProject( MavenProject mavenProject ); + protected abstract void addSourceFolderToProject(MavenProject mavenProject); } diff --git a/src/main/java/org/codehaus/mojo/templating/FilterSourcesMojo.java b/src/main/java/org/codehaus/mojo/templating/FilterSourcesMojo.java index 839102c..62dd6cd 100644 --- a/src/main/java/org/codehaus/mojo/templating/FilterSourcesMojo.java +++ b/src/main/java/org/codehaus/mojo/templating/FilterSourcesMojo.java @@ -30,37 +30,32 @@ * This mojo helps adding a filtered source folder in one go. This is typically useful if you want to use properties * coming from the POM inside parts of your source code that requires real constants, like annotations for example. */ -@Mojo( name = "filter-sources", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class FilterSourcesMojo - extends AbstractFilterSourcesMojo -{ +@Mojo(name = "filter-sources", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class FilterSourcesMojo extends AbstractFilterSourcesMojo { /** * Source directory that will be first filtered and then added as a classical source folder. */ - @Parameter( defaultValue = "${basedir}/src/main/java-templates" ) + @Parameter(defaultValue = "${basedir}/src/main/java-templates") File sourceDirectory; /** * Output folder where filtered sources will land. */ - @Parameter( defaultValue = "${project.build.directory}/generated-sources/java-templates" ) + @Parameter(defaultValue = "${project.build.directory}/generated-sources/java-templates") private File outputDirectory; @Override - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return sourceDirectory; } @Override - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return outputDirectory; } @Override - protected void addSourceFolderToProject( MavenProject mavenProject ) - { - mavenProject.addCompileSourceRoot( getOutputDirectory().getAbsolutePath() ); + protected void addSourceFolderToProject(MavenProject mavenProject) { + mavenProject.addCompileSourceRoot(getOutputDirectory().getAbsolutePath()); } } diff --git a/src/main/java/org/codehaus/mojo/templating/FilterTestSourcesMojo.java b/src/main/java/org/codehaus/mojo/templating/FilterTestSourcesMojo.java index 082eee0..1ff9f23 100644 --- a/src/main/java/org/codehaus/mojo/templating/FilterTestSourcesMojo.java +++ b/src/main/java/org/codehaus/mojo/templating/FilterTestSourcesMojo.java @@ -30,37 +30,32 @@ * This mojo helps adding a filtered source folder in one go. This is typically useful if you want to use properties * coming from the POM inside parts of your test source code that requires real constants, like annotations for example. */ -@Mojo( name = "filter-test-sources", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES, threadSafe = true ) -public class FilterTestSourcesMojo - extends AbstractFilterSourcesMojo -{ +@Mojo(name = "filter-test-sources", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES, threadSafe = true) +public class FilterTestSourcesMojo extends AbstractFilterSourcesMojo { /** * Source directory that will be first filtered and then added as a classical source folder. */ - @Parameter( defaultValue = "${basedir}/src/test/java-templates" ) + @Parameter(defaultValue = "${basedir}/src/test/java-templates") private File testSourceDirectory; /** * Output folder where filtered test sources will land. */ - @Parameter( defaultValue = "${project.build.directory}/generated-test-sources/java-templates" ) + @Parameter(defaultValue = "${project.build.directory}/generated-test-sources/java-templates") private File testOutputDirectory; @Override - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return testSourceDirectory; } @Override - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return testOutputDirectory; } @Override - protected void addSourceFolderToProject( MavenProject mavenProject ) - { - mavenProject.addTestCompileSourceRoot( getOutputDirectory().getAbsolutePath() ); + protected void addSourceFolderToProject(MavenProject mavenProject) { + mavenProject.addTestCompileSourceRoot(getOutputDirectory().getAbsolutePath()); } } diff --git a/src/test/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojoTest.java b/src/test/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojoTest.java index 1902c97..50a8734 100644 --- a/src/test/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojoTest.java +++ b/src/test/java/org/codehaus/mojo/templating/AbstractFilterSourcesMojoTest.java @@ -19,12 +19,6 @@ * under the License. */ -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.io.File; import org.apache.commons.io.FileUtils; @@ -44,15 +38,20 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + /** * @author Krzysztof Suszyński * @since 2015-11-17 */ @ExtendWith(MockitoExtension.class) -class AbstractFilterSourcesMojoTest -{ +class AbstractFilterSourcesMojoTest { @Spy - private MavenProject project = MavenProjectStub.createProjectForITExample( "sample-simple" ); + private MavenProject project = MavenProjectStub.createProjectForITExample("sample-simple"); @Mock private MavenSession session; @@ -61,88 +60,81 @@ class AbstractFilterSourcesMojoTest private MavenResourcesFiltering mavenResourcesFiltering; @Spy - private File sourceDirectory = resolve( project.getBasedir(), "src", "main", "java-templates" ); + private File sourceDirectory = resolve(project.getBasedir(), "src", "main", "java-templates"); @Spy - private File outputDirectory = resolve( new File( "target" ), "generated-sources", "java-templates" ); + private File outputDirectory = resolve(new File("target"), "generated-sources", "java-templates"); @InjectMocks private AbstractFilterSourcesMojo mojo = new FilterSourcesMojo(); @BeforeEach void before() { - File target = resolve( project.getBasedir(), outputDirectory.getPath() ); - FileUtils.deleteQuietly( target ); + File target = resolve(project.getBasedir(), outputDirectory.getPath()); + FileUtils.deleteQuietly(target); } @Test - void testGetOutputDirectory() - { + void testGetOutputDirectory() { // when File file = mojo.getOutputDirectory(); // then - assertThat( file ).isNotNull(); - assertThat( file.getPath() ).contains( "generated-sources" ); + assertThat(file).isNotNull(); + assertThat(file.getPath()).contains("generated-sources"); } @Test - void testGetSourceDirectory() - { + void testGetSourceDirectory() { // when File file = mojo.getSourceDirectory(); // then - assertThat( file ).isNotNull(); - assertThat( file ).exists(); - assertThat( file ).isDirectory(); - assertThat( file.getPath() ).contains( "src" ); - assertThat( file.getPath() ).contains( "main" ); + assertThat(file).isNotNull(); + assertThat(file).exists(); + assertThat(file).isDirectory(); + assertThat(file.getPath()).contains("src"); + assertThat(file.getPath()).contains("main"); } @Test - void testExecute() throws MojoExecutionException, MavenFilteringException - { + void testExecute() throws MojoExecutionException, MavenFilteringException { // given - doAnswer( new MockCopyAnswer() ).when( mavenResourcesFiltering ).filterResources( any( MavenResourcesExecution.class ) ); + doAnswer(new MockCopyAnswer()) + .when(mavenResourcesFiltering) + .filterResources(any(MavenResourcesExecution.class)); // when mojo.execute(); - assertThat( mojo.countCopiedFiles() ).isEqualTo( 1 ); + assertThat(mojo.countCopiedFiles()).isEqualTo(1); mojo.execute(); - assertThat( mojo.countCopiedFiles() ).isEqualTo( 0 ); + assertThat(mojo.countCopiedFiles()).isEqualTo(0); // then - verify( mavenResourcesFiltering, times( 2 ) ).filterResources( any( MavenResourcesExecution.class ) ); - verify( project, times( 2 ) ).addCompileSourceRoot( outputDirectory.getAbsolutePath() ); + verify(mavenResourcesFiltering, times(2)).filterResources(any(MavenResourcesExecution.class)); + verify(project, times(2)).addCompileSourceRoot(outputDirectory.getAbsolutePath()); } - private static class MockCopyAnswer - implements Answer - { + private static class MockCopyAnswer implements Answer { @Override - public Void answer( InvocationOnMock invocation ) - throws Throwable - { + public Void answer(InvocationOnMock invocation) throws Throwable { MavenResourcesExecution arg = (MavenResourcesExecution) invocation.getArguments()[0]; - File source = new File( arg.getResources().iterator().next().getDirectory() ); - assertThat( source ).exists(); - assertThat( source ).isDirectory(); + File source = new File(arg.getResources().iterator().next().getDirectory()); + assertThat(source).exists(); + assertThat(source).isDirectory(); File destination = arg.getOutputDirectory(); - assertThat( destination ).doesNotExist(); - FileUtils.copyDirectory( source, destination ); + assertThat(destination).doesNotExist(); + FileUtils.copyDirectory(source, destination); return null; } } - private static File resolve( File file, String... paths ) - { - StringBuilder sb = new StringBuilder( file.getPath() ); - for ( String path : paths ) - { - sb.append( File.separator ).append( path ); + private static File resolve(File file, String... paths) { + StringBuilder sb = new StringBuilder(file.getPath()); + for (String path : paths) { + sb.append(File.separator).append(path); } - return new File( sb.toString() ); + return new File(sb.toString()); } } diff --git a/src/test/java/org/codehaus/mojo/templating/FailingFilterSourcesMojoTest.java b/src/test/java/org/codehaus/mojo/templating/FailingFilterSourcesMojoTest.java index 2ec0cce..31fb3f9 100644 --- a/src/test/java/org/codehaus/mojo/templating/FailingFilterSourcesMojoTest.java +++ b/src/test/java/org/codehaus/mojo/templating/FailingFilterSourcesMojoTest.java @@ -33,35 +33,30 @@ import static org.mockito.Mockito.verifyNoInteractions; // Let's play with Parameterized, I've been wanted to do that for quite a long time :-). -public class FailingFilterSourcesMojoTest -{ +public class FailingFilterSourcesMojoTest { public File failingParam; - public static Collection getFailingParameters() - { - return Arrays.asList( new File[] { null }, new File[] { new File( "/non/existing/path/yodleyyyyeee" ) } ); + public static Collection getFailingParameters() { + return Arrays.asList(new File[] {null}, new File[] {new File("/non/existing/path/yodleyyyyeee")}); } @MethodSource("getFailingParameters") @ParameterizedTest - void testBadDirectoryDoesNotAddSourceFolder(File failingParam) - throws MojoExecutionException { - initFailingFilterSourcesMojoTest( failingParam ); - FilterSourcesMojo filterSourcesMojo = new FilterSourcesMojo() - { + void testBadDirectoryDoesNotAddSourceFolder(File failingParam) throws MojoExecutionException { + initFailingFilterSourcesMojoTest(failingParam); + FilterSourcesMojo filterSourcesMojo = new FilterSourcesMojo() { @Override - protected void addSourceFolderToProject( MavenProject mavenProject ) - { + protected void addSourceFolderToProject(MavenProject mavenProject) { throw new IllegalArgumentException(); } }; filterSourcesMojo.sourceDirectory = failingParam; - MavenResourcesFiltering mock = mock( MavenResourcesFiltering.class ); + MavenResourcesFiltering mock = mock(MavenResourcesFiltering.class); filterSourcesMojo.mavenResourcesFiltering = mock; filterSourcesMojo.execute(); - verifyNoInteractions( mock ); + verifyNoInteractions(mock); } public void initFailingFilterSourcesMojoTest(File failingParam) { diff --git a/src/test/java/org/codehaus/mojo/templating/MavenProjectStub.java b/src/test/java/org/codehaus/mojo/templating/MavenProjectStub.java index e0c01c7..c827ee9 100644 --- a/src/test/java/org/codehaus/mojo/templating/MavenProjectStub.java +++ b/src/test/java/org/codehaus/mojo/templating/MavenProjectStub.java @@ -19,8 +19,6 @@ * under the License. */ -import static org.assertj.core.api.Assertions.assertThat; - import java.io.File; import java.net.URL; import java.util.ArrayList; @@ -32,17 +30,16 @@ import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.project.MavenProject; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Krzysztof Suszyński * @since 2015-11-17 */ -public class MavenProjectStub - extends MavenProject -{ +public class MavenProjectStub extends MavenProject { private final File basedir; - public MavenProjectStub( File basedir ) - { + public MavenProjectStub(File basedir) { this.basedir = basedir; initiate(); } @@ -51,62 +48,55 @@ public MavenProjectStub( File basedir ) * {@inheritDoc} */ @Override - public File getBasedir() - { + public File getBasedir() { return basedir; } - private void initiate() - { + private void initiate() { MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model; - try ( XmlStreamReader in = new XmlStreamReader( new File( getBasedir(), "pom.xml" ) ) ) - { + try (XmlStreamReader in = new XmlStreamReader(new File(getBasedir(), "pom.xml"))) { model = pomReader.read(in); - setModel( model ); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); + setModel(model); + } catch (Exception e) { + throw new RuntimeException(e); } - setGroupId( model.getGroupId() ); - setArtifactId( model.getArtifactId() ); - setVersion( model.getVersion() ); - setName( model.getName() ); - setUrl( model.getUrl() ); - setPackaging( model.getPackaging() ); + setGroupId(model.getGroupId()); + setArtifactId(model.getArtifactId()); + setVersion(model.getVersion()); + setName(model.getName()); + setUrl(model.getUrl()); + setPackaging(model.getPackaging()); Build build = new Build(); - build.setFinalName( model.getArtifactId() ); - build.setDirectory( getBasedir() + "/target" ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setOutputDirectory( getBasedir() + "/target/classes" ); - build.setTestSourceDirectory( getBasedir() + "/src/test/java" ); - build.setTestOutputDirectory( getBasedir() + "/target/test-classes" ); - setBuild( build ); + build.setFinalName(model.getArtifactId()); + build.setDirectory(getBasedir() + "/target"); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setOutputDirectory(getBasedir() + "/target/classes"); + build.setTestSourceDirectory(getBasedir() + "/src/test/java"); + build.setTestOutputDirectory(getBasedir() + "/target/test-classes"); + setBuild(build); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); List testCompileSourceRoots = new ArrayList<>(); - testCompileSourceRoots.add( getBasedir() + "/src/test/java" ); - setTestCompileSourceRoots( testCompileSourceRoots ); + testCompileSourceRoots.add(getBasedir() + "/src/test/java"); + setTestCompileSourceRoots(testCompileSourceRoots); } - public static MavenProject createProjectForITExample( String exampleName ) - { + public static MavenProject createProjectForITExample(String exampleName) { String load = exampleName + '/' + "pom.xml"; - URL pomUrl = MavenProjectStub.class.getClassLoader().getResource( load ); + URL pomUrl = MavenProjectStub.class.getClassLoader().getResource(load); assert pomUrl != null : "Could not load: " + load; String pomPath = pomUrl.getPath(); - File pomFile = new File( pomPath ); - assertThat( pomFile ).exists().isFile(); + File pomFile = new File(pomPath); + assertThat(pomFile).exists().isFile(); File baseDir = pomFile.getParentFile(); - assertThat( baseDir ).exists().isDirectory(); - return new MavenProjectStub( baseDir ); + assertThat(baseDir).exists().isDirectory(); + return new MavenProjectStub(baseDir); } - } diff --git a/src/test/java/org/codehaus/mojo/templating/OkFilterSourcesMojoTest.java b/src/test/java/org/codehaus/mojo/templating/OkFilterSourcesMojoTest.java index ddec069..d01a71f 100644 --- a/src/test/java/org/codehaus/mojo/templating/OkFilterSourcesMojoTest.java +++ b/src/test/java/org/codehaus/mojo/templating/OkFilterSourcesMojoTest.java @@ -19,43 +19,38 @@ * under the License. */ -import static org.assertj.core.api.Assertions.assertThat; - import java.io.File; import org.apache.maven.project.MavenProject; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -class OkFilterSourcesMojoTest -{ +class OkFilterSourcesMojoTest { @Test - void testExistingDirectoryDoesNotAddSourceFolder() - { + void testExistingDirectoryDoesNotAddSourceFolder() { final StringBuilder placeholder = new StringBuilder(); - FilterSourcesMojo filterSourcesMojo = new FilterSourcesMojo() - { + FilterSourcesMojo filterSourcesMojo = new FilterSourcesMojo() { @Override - protected void addSourceFolderToProject( MavenProject mavenProject ) - { - placeholder.append( "called" ); + protected void addSourceFolderToProject(MavenProject mavenProject) { + placeholder.append("called"); } }; - filterSourcesMojo.sourceDirectory = new File( "." ); + filterSourcesMojo.sourceDirectory = new File("."); - MavenProject mock = mock( MavenProject.class ); - Mockito.doThrow( IllegalArgumentException.class ).when( mock ).addCompileSourceRoot( anyString() ); - Mockito.doThrow( IllegalArgumentException.class ).when( mock ).addTestCompileSourceRoot( anyString() ); + MavenProject mock = mock(MavenProject.class); + Mockito.doThrow(IllegalArgumentException.class).when(mock).addCompileSourceRoot(anyString()); + Mockito.doThrow(IllegalArgumentException.class).when(mock).addTestCompileSourceRoot(anyString()); - filterSourcesMojo.addSourceFolderToProject( mock ); - assertEquals( "called", placeholder.toString() ); - assertThat( placeholder.toString() ).isEqualTo( "called" ); - verify( mock, never() ).addTestCompileSourceRoot( anyString() ); + filterSourcesMojo.addSourceFolderToProject(mock); + assertEquals("called", placeholder.toString()); + assertThat(placeholder.toString()).isEqualTo("called"); + verify(mock, never()).addTestCompileSourceRoot(anyString()); } }