diff --git a/pom.xml b/pom.xml index 95c032f7a..978fc3af8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - + - 4.0.0 @@ -36,31 +34,6 @@ under the License. Apache Maven Dependency Plugin Provides utility goals to work with dependencies like copying, unpacking, analyzing, resolving and many more. - - ${mavenVersion} - - - - scm:git:https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git - scm:git:https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git - https://github.com/apache/maven-dependency-plugin/tree/${project.scm.tag} - HEAD - - - JIRA - https://issues.apache.org/jira/browse/MDEP - - - Jenkins - https://ci-maven.apache.org/job/Maven/job/maven-box/job/maven-dependency-plugin/ - - - - apache.website - scm:svn:https://svn.apache.org/repos/asf/maven/website/components/${maven.site.path} - - - Bakito @@ -88,6 +61,31 @@ under the License. + + ${mavenVersion} + + + + scm:git:https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git + scm:git:https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git + HEAD + https://github.com/apache/maven-dependency-plugin/tree/${project.scm.tag} + + + JIRA + https://issues.apache.org/jira/browse/MDEP + + + Jenkins + https://ci-maven.apache.org/job/Maven/job/maven-box/job/maven-dependency-plugin/ + + + + apache.website + scm:svn:https://svn.apache.org/repos/asf/maven/website/components/${maven.site.path} + + + 3.2.5 9.4.49.v20220914 @@ -160,7 +158,7 @@ under the License. ${mavenVersion} provided - + org.apache.maven.reporting @@ -235,7 +233,7 @@ under the License. maven-plugin-annotations provided - + org.eclipse.aether aether-api @@ -252,10 +250,11 @@ under the License. org.sonatype.plexus plexus-build-api - 0.0.7 + 0.0.7 + compile - + org.eclipse.aether @@ -428,14 +427,6 @@ under the License. org.codehaus.mojo mrm-maven-plugin 1.4.1 - - - - start - stop - - - repository.proxy.url @@ -445,9 +436,17 @@ under the License. ${project.build.directory}/local-repo - + + + + + start + stop + + + diff --git a/src/main/java/org/apache/maven/plugins/dependency/AbstractDependencyMojo.java b/src/main/java/org/apache/maven/plugins/dependency/AbstractDependencyMojo.java index 5294bef87..66c64c8e2 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/AbstractDependencyMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/AbstractDependencyMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.execution.MavenSession; @@ -51,16 +49,13 @@ /** * @author Brian Fox */ -public abstract class AbstractDependencyMojo - extends AbstractMojo -{ +public abstract class AbstractDependencyMojo extends AbstractMojo { /** * To look up Archiver/UnArchiver implementations */ @Component private ArchiverManager archiverManager; - /** * For IDE build support */ @@ -69,11 +64,11 @@ public abstract class AbstractDependencyMojo /** * Skip plugin execution only during incremental builds (e.g. triggered from M2E). - * + * * @since 3.4.0 * @see #skip */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean skipDuringIncrementalBuild; /** @@ -81,48 +76,48 @@ public abstract class AbstractDependencyMojo * will use the jvm chmod, this is available for user and all level group level will be ignored *

* since 2.6 is on by default - * + * * @since 2.5.1 */ - @Parameter( property = "dependency.useJvmChmod", defaultValue = "true" ) + @Parameter(property = "dependency.useJvmChmod", defaultValue = "true") private boolean useJvmChmod = true; /** * ignore to set file permissions when unpacking a dependency - * + * * @since 2.7 */ - @Parameter( property = "dependency.ignorePermissions", defaultValue = "false" ) + @Parameter(property = "dependency.ignorePermissions", defaultValue = "false") private boolean ignorePermissions; /** * POM */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * Remote repositories which will be searched for artifacts. */ - @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true) private List remoteRepositories; /** * Remote repositories which will be searched for plugins. */ - @Parameter( defaultValue = "${project.pluginArtifactRepositories}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.pluginArtifactRepositories}", readonly = true, required = true) private List remotePluginRepositories; /** * Contains the full list of projects in the reactor. */ - @Parameter( defaultValue = "${reactorProjects}", readonly = true ) + @Parameter(defaultValue = "${reactorProjects}", readonly = true) protected List reactorProjects; /** * The Maven session */ - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; /** @@ -130,7 +125,7 @@ public abstract class AbstractDependencyMojo * * @since 2.0 */ - @Parameter( property = "silent", defaultValue = "false" ) + @Parameter(property = "silent", defaultValue = "false") private boolean silent; /** @@ -138,7 +133,7 @@ public abstract class AbstractDependencyMojo * * @since 2.0 */ - @Parameter( property = "outputAbsoluteArtifactFilename", defaultValue = "false" ) + @Parameter(property = "outputAbsoluteArtifactFilename", defaultValue = "false") protected boolean outputAbsoluteArtifactFilename; /** @@ -146,7 +141,7 @@ public abstract class AbstractDependencyMojo * * @since 2.7 */ - @Parameter( property = "mdep.skip", defaultValue = "false" ) + @Parameter(property = "mdep.skip", defaultValue = "false") private boolean skip; // Mojo methods ----------------------------------------------------------- @@ -155,12 +150,9 @@ public abstract class AbstractDependencyMojo * @see org.apache.maven.plugin.Mojo#execute() */ @Override - public final void execute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { - getLog().info( "Skipping plugin execution" ); + public final void execute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { + getLog().info("Skipping plugin execution"); return; } @@ -171,14 +163,12 @@ public final void execute() * @throws MojoExecutionException {@link MojoExecutionException} * @throws MojoFailureException {@link MojoFailureException} */ - protected abstract void doExecute() - throws MojoExecutionException, MojoFailureException; + protected abstract void doExecute() throws MojoExecutionException, MojoFailureException; /** * @return Returns the archiverManager. */ - public ArchiverManager getArchiverManager() - { + public ArchiverManager getArchiverManager() { return this.archiverManager; } @@ -189,28 +179,22 @@ public ArchiverManager getArchiverManager() * @param destFile file name of destination file. * @throws MojoExecutionException with a message if an error occurs. */ - protected void copyFile( File artifact, File destFile ) - throws MojoExecutionException - { - try - { - getLog().info( "Copying " - + ( this.outputAbsoluteArtifactFilename ? artifact.getAbsolutePath() : artifact.getName() ) + " to " - + destFile ); - - if ( artifact.isDirectory() ) - { + protected void copyFile(File artifact, File destFile) throws MojoExecutionException { + try { + getLog().info("Copying " + + (this.outputAbsoluteArtifactFilename ? artifact.getAbsolutePath() : artifact.getName()) + " to " + + destFile); + + if (artifact.isDirectory()) { // usual case is a future jar packaging, but there are special cases: classifier and other packaging - throw new MojoExecutionException( "Artifact has not been packaged yet. When used on reactor artifact, " - + "copy should be executed after packaging: see MDEP-187." ); + throw new MojoExecutionException("Artifact has not been packaged yet. When used on reactor artifact, " + + "copy should be executed after packaging: see MDEP-187."); } - FileUtils.copyFile( artifact, destFile ); - buildContext.refresh( destFile ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Error copying artifact from " + artifact + " to " + destFile, e ); + FileUtils.copyFile(artifact, destFile); + buildContext.refresh(destFile); + } catch (IOException e) { + throw new MojoExecutionException("Error copying artifact from " + artifact + " to " + destFile, e); } } @@ -222,10 +206,9 @@ protected void copyFile( File artifact, File destFile ) * shall happen. * @throws MojoExecutionException in case of an error. */ - protected void unpack( Artifact artifact, File location, String encoding, FileMapper[] fileMappers ) - throws MojoExecutionException - { - unpack( artifact, location, null, null, encoding, fileMappers ); + protected void unpack(Artifact artifact, File location, String encoding, FileMapper[] fileMappers) + throws MojoExecutionException { + unpack(artifact, location, null, null, encoding, fileMappers); } /** @@ -242,10 +225,15 @@ protected void unpack( Artifact artifact, File location, String encoding, FileMa * shall happen. * @throws MojoExecutionException In case of errors. */ - protected void unpack( Artifact artifact, File location, String includes, String excludes, String encoding, - FileMapper[] fileMappers ) throws MojoExecutionException - { - unpack( artifact, artifact.getType(), location, includes, excludes, encoding, fileMappers ); + protected void unpack( + Artifact artifact, + File location, + String includes, + String excludes, + String encoding, + FileMapper[] fileMappers) + throws MojoExecutionException { + unpack(artifact, artifact.getType(), location, includes, excludes, encoding, fileMappers); } /** @@ -259,107 +247,93 @@ protected void unpack( Artifact artifact, File location, String includes, String * shall happen. * @throws MojoExecutionException in case of an error. */ - protected void unpack( Artifact artifact, String type, File location, String includes, String excludes, - String encoding, FileMapper[] fileMappers ) - throws MojoExecutionException - { + protected void unpack( + Artifact artifact, + String type, + File location, + String includes, + String excludes, + String encoding, + FileMapper[] fileMappers) + throws MojoExecutionException { File file = artifact.getFile(); - try - { - logUnpack( file, location, includes, excludes ); + try { + logUnpack(file, location, includes, excludes); location.mkdirs(); - if ( !location.exists() ) - { - throw new MojoExecutionException( "Location to write unpacked files to could not be created: " - + location ); + if (!location.exists()) { + throw new MojoExecutionException( + "Location to write unpacked files to could not be created: " + location); } - if ( file.isDirectory() ) - { + if (file.isDirectory()) { // usual case is a future jar packaging, but there are special cases: classifier and other packaging - throw new MojoExecutionException( "Artifact has not been packaged yet. When used on reactor artifact, " - + "unpack should be executed after packaging: see MDEP-98." ); + throw new MojoExecutionException("Artifact has not been packaged yet. When used on reactor artifact, " + + "unpack should be executed after packaging: see MDEP-98."); } UnArchiver unArchiver; - try - { - unArchiver = archiverManager.getUnArchiver( type ); - getLog().debug( "Found unArchiver by type: " + unArchiver ); - } - catch ( NoSuchArchiverException e ) - { - unArchiver = archiverManager.getUnArchiver( file ); - getLog().debug( "Found unArchiver by extension: " + unArchiver ); + try { + unArchiver = archiverManager.getUnArchiver(type); + getLog().debug("Found unArchiver by type: " + unArchiver); + } catch (NoSuchArchiverException e) { + unArchiver = archiverManager.getUnArchiver(file); + getLog().debug("Found unArchiver by extension: " + unArchiver); } - if ( encoding != null && unArchiver instanceof ZipUnArchiver ) - { - ( (ZipUnArchiver) unArchiver ).setEncoding( encoding ); - getLog().info( "Unpacks '" + type + "' with encoding '" + encoding + "'." ); + if (encoding != null && unArchiver instanceof ZipUnArchiver) { + ((ZipUnArchiver) unArchiver).setEncoding(encoding); + getLog().info("Unpacks '" + type + "' with encoding '" + encoding + "'."); } - unArchiver.setIgnorePermissions( ignorePermissions ); + unArchiver.setIgnorePermissions(ignorePermissions); - unArchiver.setSourceFile( file ); + unArchiver.setSourceFile(file); - unArchiver.setDestDirectory( location ); + unArchiver.setDestDirectory(location); - if ( StringUtils.isNotEmpty( excludes ) || StringUtils.isNotEmpty( includes ) ) - { + if (StringUtils.isNotEmpty(excludes) || StringUtils.isNotEmpty(includes)) { // Create the selectors that will filter // based on include/exclude parameters // MDEP-47 IncludeExcludeFileSelector[] selectors = - new IncludeExcludeFileSelector[] { new IncludeExcludeFileSelector() }; + new IncludeExcludeFileSelector[] {new IncludeExcludeFileSelector()}; - if ( StringUtils.isNotEmpty( excludes ) ) - { - selectors[0].setExcludes( excludes.split( "," ) ); + if (StringUtils.isNotEmpty(excludes)) { + selectors[0].setExcludes(excludes.split(",")); } - if ( StringUtils.isNotEmpty( includes ) ) - { - selectors[0].setIncludes( includes.split( "," ) ); + if (StringUtils.isNotEmpty(includes)) { + selectors[0].setIncludes(includes.split(",")); } - unArchiver.setFileSelectors( selectors ); + unArchiver.setFileSelectors(selectors); } - if ( this.silent ) - { - silenceUnarchiver( unArchiver ); + if (this.silent) { + silenceUnarchiver(unArchiver); } - unArchiver.setFileMappers( fileMappers ); + unArchiver.setFileMappers(fileMappers); unArchiver.extract(); + } catch (NoSuchArchiverException e) { + throw new MojoExecutionException("Unknown archiver type", e); + } catch (ArchiverException e) { + throw new MojoExecutionException("Error unpacking file: " + file + " to: " + location, e); } - catch ( NoSuchArchiverException e ) - { - throw new MojoExecutionException( "Unknown archiver type", e ); - } - catch ( ArchiverException e ) - { - throw new MojoExecutionException( "Error unpacking file: " + file + " to: " + location, e ); - } - buildContext.refresh( location ); + buildContext.refresh(location); } - private void silenceUnarchiver( UnArchiver unArchiver ) - { + private void silenceUnarchiver(UnArchiver unArchiver) { // dangerous but handle any errors. It's the only way to silence the unArchiver. - try - { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( "logger", unArchiver.getClass() ); + try { + Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses("logger", unArchiver.getClass()); - field.setAccessible( true ); + field.setAccessible(true); - field.set( unArchiver, this.getLog() ); - } - catch ( Exception e ) - { + field.set(unArchiver, this.getLog()); + } catch (Exception e) { // was a nice try. Don't bother logging because the log is silent. } } @@ -368,26 +342,22 @@ private void silenceUnarchiver( UnArchiver unArchiver ) * @return Returns a new ProjectBuildingRequest populated from the current session and the current project remote * repositories, used to resolve artifacts. */ - public ProjectBuildingRequest newResolveArtifactProjectBuildingRequest() - { - return newProjectBuildingRequest( remoteRepositories ); + public ProjectBuildingRequest newResolveArtifactProjectBuildingRequest() { + return newProjectBuildingRequest(remoteRepositories); } /** * @return Returns a new ProjectBuildingRequest populated from the current session and the current project remote * repositories, used to resolve plugins. */ - protected ProjectBuildingRequest newResolvePluginProjectBuildingRequest() - { - return newProjectBuildingRequest( remotePluginRepositories ); + protected ProjectBuildingRequest newResolvePluginProjectBuildingRequest() { + return newProjectBuildingRequest(remotePluginRepositories); } - private ProjectBuildingRequest newProjectBuildingRequest( List repositories ) - { - ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); + private ProjectBuildingRequest newProjectBuildingRequest(List repositories) { + ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); - buildingRequest.setRemoteRepositories( repositories ); + buildingRequest.setRemoteRepositories(repositories); return buildingRequest; } @@ -395,42 +365,36 @@ private ProjectBuildingRequest newProjectBuildingRequest( List ancestors = collectAncestors(); - if ( ancestors.isEmpty() ) - { - getLog().info( "No Ancestor POMs!" ); + if (ancestors.isEmpty()) { + getLog().info("No Ancestor POMs!"); + } else { + getLog().info(String.format(Locale.US, "Ancestor POMs: %s", StringUtils.join(ancestors, " <- "))); } - else - { - getLog().info( String.format( Locale.US, "Ancestor POMs: %s", StringUtils.join( ancestors, " <- " ) ) ); - } - } - private ArrayList collectAncestors() - { + private ArrayList collectAncestors() { final ArrayList ancestors = new ArrayList<>(); MavenProject currentAncestor = project.getParent(); - while ( currentAncestor != null ) - { - final String gav = String.format( Locale.US, "%s:%s:%s", currentAncestor.getGroupId(), - currentAncestor.getArtifactId(), currentAncestor.getVersion() ); + while (currentAncestor != null) { + final String gav = String.format( + Locale.US, + "%s:%s:%s", + currentAncestor.getGroupId(), + currentAncestor.getArtifactId(), + currentAncestor.getVersion()); - ancestors.add( gav ); + ancestors.add(gav); currentAncestor = currentAncestor.getParent(); } return ancestors; } - } diff --git a/src/main/java/org/apache/maven/plugins/dependency/GetMojo.java b/src/main/java/org/apache/maven/plugins/dependency/GetMojo.java index 9ddbff35b..283c753c4 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/GetMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/GetMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -56,13 +54,11 @@ * Resolves a single artifact, eventually transitively, from the specified remote repositories. Caveat: will always * check the central repository defined in the super pom. You could use a mirror entry in your settings.xml */ -@Mojo( name = "get", requiresProject = false, threadSafe = true ) -public class GetMojo - extends AbstractMojo -{ - private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile( "(.+)::(.*)::(.+)" ); +@Mojo(name = "get", requiresProject = false, threadSafe = true) +public class GetMojo extends AbstractMojo { + private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile("(.+)::(.*)::(.+)"); - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) private MavenSession session; @Component @@ -77,7 +73,7 @@ public class GetMojo /** * Map that contains the layouts. */ - @Component( role = ArtifactRepositoryLayout.class ) + @Component(role = ArtifactRepositoryLayout.class) private Map repositoryLayouts; /** @@ -91,19 +87,19 @@ public class GetMojo /** * The groupId of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "groupId" ) + @Parameter(property = "groupId") private String groupId; /** * The artifactId of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "artifactId" ) + @Parameter(property = "artifactId") private String artifactId; /** * The version of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "version" ) + @Parameter(property = "version") private String version; /** @@ -111,38 +107,38 @@ public class GetMojo * * @since 2.3 */ - @Parameter( property = "classifier" ) + @Parameter(property = "classifier") private String classifier; /** * The packaging of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "packaging", defaultValue = "jar" ) + @Parameter(property = "packaging", defaultValue = "jar") private String packaging = "jar"; /** * Repositories in the format id::[layout]::url or just url, separated by comma. ie. * central::default::https://repo.maven.apache.org/maven2,myrepo::::https://repo.acme.com,https://repo.acme2.com */ - @Parameter( property = "remoteRepositories" ) + @Parameter(property = "remoteRepositories") private String remoteRepositories; /** * A string of the form groupId:artifactId:version[:packaging[:classifier]]. */ - @Parameter( property = "artifact" ) + @Parameter(property = "artifact") private String artifact; /** * */ - @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true) private List pomRemoteRepositories; /** * Download transitively, retrieving the specified artifact and all of its dependencies. */ - @Parameter( property = "transitive", defaultValue = "true" ) + @Parameter(property = "transitive", defaultValue = "true") private boolean transitive = true; /** @@ -150,143 +146,118 @@ public class GetMojo * * @since 2.7 */ - @Parameter( property = "mdep.skip", defaultValue = "false" ) + @Parameter(property = "mdep.skip", defaultValue = "false") private boolean skip; @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { + getLog().info("Skipping plugin execution"); return; } - if ( coordinate.getArtifactId() == null && artifact == null ) - { - throw new MojoFailureException( "You must specify an artifact, " - + "e.g. -Dartifact=org.apache.maven.plugins:maven-downloader-plugin:1.0" ); + if (coordinate.getArtifactId() == null && artifact == null) { + throw new MojoFailureException("You must specify an artifact, " + + "e.g. -Dartifact=org.apache.maven.plugins:maven-downloader-plugin:1.0"); } - if ( artifact != null ) - { - String[] tokens = StringUtils.split( artifact, ":" ); - if ( tokens.length < 3 || tokens.length > 5 ) - { - throw new MojoFailureException( "Invalid artifact, you must specify " - + "groupId:artifactId:version[:packaging[:classifier]] " + artifact ); + if (artifact != null) { + String[] tokens = StringUtils.split(artifact, ":"); + if (tokens.length < 3 || tokens.length > 5) { + throw new MojoFailureException("Invalid artifact, you must specify " + + "groupId:artifactId:version[:packaging[:classifier]] " + artifact); } - coordinate.setGroupId( tokens[0] ); - coordinate.setArtifactId( tokens[1] ); - coordinate.setVersion( tokens[2] ); - if ( tokens.length >= 4 ) - { - coordinate.setType( tokens[3] ); + coordinate.setGroupId(tokens[0]); + coordinate.setArtifactId(tokens[1]); + coordinate.setVersion(tokens[2]); + if (tokens.length >= 4) { + coordinate.setType(tokens[3]); } - if ( tokens.length == 5 ) - { - coordinate.setClassifier( tokens[4] ); + if (tokens.length == 5) { + coordinate.setClassifier(tokens[4]); } } - ArtifactRepositoryPolicy always = - new ArtifactRepositoryPolicy( true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN ); + ArtifactRepositoryPolicy always = new ArtifactRepositoryPolicy( + true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); List repoList = new ArrayList<>(); - if ( pomRemoteRepositories != null ) - { - repoList.addAll( pomRemoteRepositories ); + if (pomRemoteRepositories != null) { + repoList.addAll(pomRemoteRepositories); } - if ( remoteRepositories != null ) - { + if (remoteRepositories != null) { // Use the same format as in the deploy plugin id::layout::url - String[] repos = StringUtils.split( remoteRepositories, "," ); - for ( String repo : repos ) - { - repoList.add( parseRepository( repo, always ) ); + String[] repos = StringUtils.split(remoteRepositories, ","); + for (String repo : repos) { + repoList.add(parseRepository(repo, always)); } } - try - { + try { ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); + new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); Settings settings = session.getSettings(); - repositorySystem.injectMirror( repoList, settings.getMirrors() ); - repositorySystem.injectProxy( repoList, settings.getProxies() ); - repositorySystem.injectAuthentication( repoList, settings.getServers() ); - - buildingRequest.setRemoteRepositories( repoList ); - - if ( transitive ) - { - getLog().info( "Resolving " + coordinate + " with transitive dependencies" ); - dependencyResolver.resolveDependencies( buildingRequest, coordinate, null ); - } - else - { - getLog().info( "Resolving " + coordinate ); - artifactResolver.resolveArtifact( buildingRequest, toArtifactCoordinate( coordinate ) ); + repositorySystem.injectMirror(repoList, settings.getMirrors()); + repositorySystem.injectProxy(repoList, settings.getProxies()); + repositorySystem.injectAuthentication(repoList, settings.getServers()); + + buildingRequest.setRemoteRepositories(repoList); + + if (transitive) { + getLog().info("Resolving " + coordinate + " with transitive dependencies"); + dependencyResolver.resolveDependencies(buildingRequest, coordinate, null); + } else { + getLog().info("Resolving " + coordinate); + artifactResolver.resolveArtifact(buildingRequest, toArtifactCoordinate(coordinate)); } - } - catch ( ArtifactResolverException | DependencyResolverException e ) - { - throw new MojoExecutionException( "Couldn't download artifact: " + e.getMessage(), e ); + } catch (ArtifactResolverException | DependencyResolverException e) { + throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e); } } - private ArtifactCoordinate toArtifactCoordinate( DependableCoordinate dependableCoordinate ) - { - ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler( dependableCoordinate.getType() ); + private ArtifactCoordinate toArtifactCoordinate(DependableCoordinate dependableCoordinate) { + ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler(dependableCoordinate.getType()); DefaultArtifactCoordinate artifactCoordinate = new DefaultArtifactCoordinate(); - artifactCoordinate.setGroupId( dependableCoordinate.getGroupId() ); - artifactCoordinate.setArtifactId( dependableCoordinate.getArtifactId() ); - artifactCoordinate.setVersion( dependableCoordinate.getVersion() ); - artifactCoordinate.setClassifier( dependableCoordinate.getClassifier() ); - artifactCoordinate.setExtension( artifactHandler.getExtension() ); + artifactCoordinate.setGroupId(dependableCoordinate.getGroupId()); + artifactCoordinate.setArtifactId(dependableCoordinate.getArtifactId()); + artifactCoordinate.setVersion(dependableCoordinate.getVersion()); + artifactCoordinate.setClassifier(dependableCoordinate.getClassifier()); + artifactCoordinate.setExtension(artifactHandler.getExtension()); return artifactCoordinate; } - ArtifactRepository parseRepository( String repo, ArtifactRepositoryPolicy policy ) - throws MojoFailureException - { + ArtifactRepository parseRepository(String repo, ArtifactRepositoryPolicy policy) throws MojoFailureException { // if it's a simple url String id = "temp"; - ArtifactRepositoryLayout layout = getLayout( "default" ); + ArtifactRepositoryLayout layout = getLayout("default"); String url = repo; // if it's an extended repo URL of the form id::layout::url - if ( repo.contains( "::" ) ) - { - Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher( repo ); - if ( !matcher.matches() ) - { - throw new MojoFailureException( repo, "Invalid syntax for repository: " + repo, - "Invalid syntax for repository. Use \"id::layout::url\" or \"URL\"." ); + if (repo.contains("::")) { + Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher(repo); + if (!matcher.matches()) { + throw new MojoFailureException( + repo, + "Invalid syntax for repository: " + repo, + "Invalid syntax for repository. Use \"id::layout::url\" or \"URL\"."); } - id = matcher.group( 1 ).trim(); - if ( !StringUtils.isEmpty( matcher.group( 2 ) ) ) - { - layout = getLayout( matcher.group( 2 ).trim() ); + id = matcher.group(1).trim(); + if (!StringUtils.isEmpty(matcher.group(2))) { + layout = getLayout(matcher.group(2).trim()); } - url = matcher.group( 3 ).trim(); + url = matcher.group(3).trim(); } - return new MavenArtifactRepository( id, url, layout, policy, policy ); + return new MavenArtifactRepository(id, url, layout, policy, policy); } - private ArtifactRepositoryLayout getLayout( String id ) - throws MojoFailureException - { - ArtifactRepositoryLayout layout = repositoryLayouts.get( id ); + private ArtifactRepositoryLayout getLayout(String id) throws MojoFailureException { + ArtifactRepositoryLayout layout = repositoryLayouts.get(id); - if ( layout == null ) - { - throw new MojoFailureException( id, "Invalid repository layout", "Invalid repository layout: " + id ); + if (layout == null) { + throw new MojoFailureException(id, "Invalid repository layout", "Invalid repository layout: " + id); } return layout; @@ -295,49 +266,42 @@ private ArtifactRepositoryLayout getLayout( String id ) /** * @return {@link #skip} */ - protected boolean isSkip() - { + protected boolean isSkip() { return skip; } /** * @param groupId The groupId. */ - public void setGroupId( String groupId ) - { - this.coordinate.setGroupId( groupId ); + public void setGroupId(String groupId) { + this.coordinate.setGroupId(groupId); } /** * @param artifactId The artifactId. */ - public void setArtifactId( String artifactId ) - { - this.coordinate.setArtifactId( artifactId ); + public void setArtifactId(String artifactId) { + this.coordinate.setArtifactId(artifactId); } /** * @param version The version. */ - public void setVersion( String version ) - { - this.coordinate.setVersion( version ); + public void setVersion(String version) { + this.coordinate.setVersion(version); } /** * @param classifier The classifier to be used. */ - public void setClassifier( String classifier ) - { - this.coordinate.setClassifier( classifier ); + public void setClassifier(String classifier) { + this.coordinate.setClassifier(classifier); } /** * @param type packaging. */ - public void setPackaging( String type ) - { - this.coordinate.setType( type ); + public void setPackaging(String type) { + this.coordinate.setType(type); } - } diff --git a/src/main/java/org/apache/maven/plugins/dependency/ListClassesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/ListClassesMojo.java index 250806c4f..18b11b0d1 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/ListClassesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/ListClassesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.io.IOException; import java.util.ArrayList; @@ -28,7 +27,6 @@ import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -56,17 +54,14 @@ import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolver; import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolverException; - /** * Retrieves and lists all classes contained in the specified artifact from the specified remote repositories. */ -@Mojo( name = "list-classes", requiresProject = false, threadSafe = true ) -public class ListClassesMojo - extends AbstractMojo -{ - private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile( "(.+)::(.*)::(.+)" ); +@Mojo(name = "list-classes", requiresProject = false, threadSafe = true) +public class ListClassesMojo extends AbstractMojo { + private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile("(.+)::(.*)::(.+)"); - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) private MavenSession session; @Component @@ -81,7 +76,7 @@ public class ListClassesMojo /** * Map that contains the layouts. */ - @Component( role = ArtifactRepositoryLayout.class ) + @Component(role = ArtifactRepositoryLayout.class) private Map repositoryLayouts; /** @@ -95,19 +90,19 @@ public class ListClassesMojo /** * The group ID of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "groupId" ) + @Parameter(property = "groupId") private String groupId; /** * The artifact ID of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "artifactId" ) + @Parameter(property = "artifactId") private String artifactId; /** * The version of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "version" ) + @Parameter(property = "version") private String version; /** @@ -115,209 +110,179 @@ public class ListClassesMojo * * @since 2.3 */ - @Parameter( property = "classifier" ) + @Parameter(property = "classifier") private String classifier; /** * The packaging of the artifact to download. Ignored if {@link #artifact} is used. */ - @Parameter( property = "packaging", defaultValue = "jar" ) + @Parameter(property = "packaging", defaultValue = "jar") private String packaging = "jar"; /** * Repositories in the format id::[layout]::url or just URLs, separated by comma. That is, * central::default::https://repo.maven.apache.org/maven2,myrepo::::https://repo.acme.com,https://repo.acme2.com */ - @Parameter( property = "remoteRepositories" ) + @Parameter(property = "remoteRepositories") private String remoteRepositories; /** * A string of the form groupId:artifactId:version[:packaging[:classifier]]. */ - @Parameter( property = "artifact" ) + @Parameter(property = "artifact") private String artifact; - @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true) private List pomRemoteRepositories; /** * Download transitively, retrieving the specified artifact and all of its dependencies. */ - @Parameter( property = "transitive", defaultValue = "false" ) + @Parameter(property = "transitive", defaultValue = "false") private boolean transitive = false; /** * Skip plugin execution completely. */ - @Parameter( property = "mdep.skip", defaultValue = "false" ) + @Parameter(property = "mdep.skip", defaultValue = "false") private boolean skip; @Override - public void execute() throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { ProjectBuildingRequest buildingRequest = makeBuildingRequest(); - try - { - if ( transitive ) - { - Iterable artifacts = dependencyResolver - .resolveDependencies( buildingRequest, coordinate, null ); + try { + if (transitive) { + Iterable artifacts = + dependencyResolver.resolveDependencies(buildingRequest, coordinate, null); - for ( ArtifactResult result : artifacts ) - { - printClassesFromArtifactResult( result ); + for (ArtifactResult result : artifacts) { + printClassesFromArtifactResult(result); } - } - else - { - ArtifactResult result = artifactResolver - .resolveArtifact( buildingRequest, toArtifactCoordinate( coordinate ) ); + } else { + ArtifactResult result = + artifactResolver.resolveArtifact(buildingRequest, toArtifactCoordinate(coordinate)); - printClassesFromArtifactResult( result ); + printClassesFromArtifactResult(result); } - } - catch ( ArtifactResolverException | DependencyResolverException | IOException e ) - { - throw new MojoExecutionException( "Couldn't download artifact: " + e.getMessage(), e ); + } catch (ArtifactResolverException | DependencyResolverException | IOException e) { + throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e); } } - private void printClassesFromArtifactResult( ArtifactResult result ) - throws IOException - { + private void printClassesFromArtifactResult(ArtifactResult result) throws IOException { // open jar file in try-with-resources statement to guarantee the file closes after use regardless of errors - try ( JarFile jarFile = new JarFile( result.getArtifact().getFile() ) ) - { + try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) { Enumeration entries = jarFile.entries(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); // filter out files that do not end in .class - if ( !entryName.endsWith( ".class" ) ) - { + if (!entryName.endsWith(".class")) { continue; } // remove .class from the end and change format to use periods instead of forward slashes - String className = entryName.substring( 0, entryName.length() - 6 ).replace( '/', '.' ); - getLog().info( className ); + String className = + entryName.substring(0, entryName.length() - 6).replace('/', '.'); + getLog().info(className); } } } - private ProjectBuildingRequest makeBuildingRequest() - throws MojoExecutionException, MojoFailureException - { - if ( artifact == null ) - { - throw new MojoFailureException( "You must specify an artifact, " - + "e.g. -Dartifact=org.apache.maven.plugins:maven-downloader-plugin:1.0" ); + private ProjectBuildingRequest makeBuildingRequest() throws MojoExecutionException, MojoFailureException { + if (artifact == null) { + throw new MojoFailureException("You must specify an artifact, " + + "e.g. -Dartifact=org.apache.maven.plugins:maven-downloader-plugin:1.0"); } - String[] tokens = artifact.split( ":" ); - if ( tokens.length < 3 || tokens.length > 5 ) - { - throw new MojoFailureException( "Invalid artifact, you must specify " - + "groupId:artifactId:version[:packaging[:classifier]] " + artifact ); + String[] tokens = artifact.split(":"); + if (tokens.length < 3 || tokens.length > 5) { + throw new MojoFailureException("Invalid artifact, you must specify " + + "groupId:artifactId:version[:packaging[:classifier]] " + artifact); } - coordinate.setGroupId( tokens[0] ); - coordinate.setArtifactId( tokens[1] ); - coordinate.setVersion( tokens[2] ); - if ( tokens.length >= 4 ) - { - coordinate.setType( tokens[3] ); + coordinate.setGroupId(tokens[0]); + coordinate.setArtifactId(tokens[1]); + coordinate.setVersion(tokens[2]); + if (tokens.length >= 4) { + coordinate.setType(tokens[3]); } - if ( tokens.length == 5 ) - { - coordinate.setClassifier( tokens[4] ); + if (tokens.length == 5) { + coordinate.setClassifier(tokens[4]); } - - ArtifactRepositoryPolicy always = - new ArtifactRepositoryPolicy( true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN ); + ArtifactRepositoryPolicy always = new ArtifactRepositoryPolicy( + true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); List repoList = new ArrayList<>(); - if ( pomRemoteRepositories != null ) - { - repoList.addAll( pomRemoteRepositories ); + if (pomRemoteRepositories != null) { + repoList.addAll(pomRemoteRepositories); } - if ( remoteRepositories != null ) - { + if (remoteRepositories != null) { // Use the same format as in the deploy plugin id::layout::url - String[] repos = remoteRepositories.split( "," ); - for ( String repo : repos ) - { - repoList.add( parseRepository( repo, always ) ); + String[] repos = remoteRepositories.split(","); + for (String repo : repos) { + repoList.add(parseRepository(repo, always)); } } - ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); + ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); Settings settings = session.getSettings(); - repositorySystem.injectMirror( repoList, settings.getMirrors() ); - repositorySystem.injectProxy( repoList, settings.getProxies() ); - repositorySystem.injectAuthentication( repoList, settings.getServers() ); + repositorySystem.injectMirror(repoList, settings.getMirrors()); + repositorySystem.injectProxy(repoList, settings.getProxies()); + repositorySystem.injectAuthentication(repoList, settings.getServers()); - buildingRequest.setRemoteRepositories( repoList ); + buildingRequest.setRemoteRepositories(repoList); return buildingRequest; } - private ArtifactCoordinate toArtifactCoordinate( DependableCoordinate dependableCoordinate ) - { - ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler( dependableCoordinate.getType() ); + private ArtifactCoordinate toArtifactCoordinate(DependableCoordinate dependableCoordinate) { + ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler(dependableCoordinate.getType()); DefaultArtifactCoordinate artifactCoordinate = new DefaultArtifactCoordinate(); - artifactCoordinate.setGroupId( dependableCoordinate.getGroupId() ); - artifactCoordinate.setArtifactId( dependableCoordinate.getArtifactId() ); - artifactCoordinate.setVersion( dependableCoordinate.getVersion() ); - artifactCoordinate.setClassifier( dependableCoordinate.getClassifier() ); - artifactCoordinate.setExtension( artifactHandler.getExtension() ); + artifactCoordinate.setGroupId(dependableCoordinate.getGroupId()); + artifactCoordinate.setArtifactId(dependableCoordinate.getArtifactId()); + artifactCoordinate.setVersion(dependableCoordinate.getVersion()); + artifactCoordinate.setClassifier(dependableCoordinate.getClassifier()); + artifactCoordinate.setExtension(artifactHandler.getExtension()); return artifactCoordinate; } - protected ArtifactRepository parseRepository( String repo, ArtifactRepositoryPolicy policy ) - throws MojoFailureException - { + protected ArtifactRepository parseRepository(String repo, ArtifactRepositoryPolicy policy) + throws MojoFailureException { // if it's a simple url String id = "temp"; - ArtifactRepositoryLayout layout = getLayout( "default" ); + ArtifactRepositoryLayout layout = getLayout("default"); // if it's an extended repo URL of the form id::layout::url - if ( repo.contains( "::" ) ) - { - Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher( repo ); - if ( !matcher.matches() ) - { - throw new MojoFailureException( repo, "Invalid syntax for repository: " + repo, - "Invalid syntax for repository. Use \"id::layout::url\" or \"URL\"." ); + if (repo.contains("::")) { + Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher(repo); + if (!matcher.matches()) { + throw new MojoFailureException( + repo, + "Invalid syntax for repository: " + repo, + "Invalid syntax for repository. Use \"id::layout::url\" or \"URL\"."); } - id = matcher.group( 1 ).trim(); - if ( !( matcher.group( 2 ) == null || matcher.group( 2 ).trim().isEmpty() ) ) - { - layout = getLayout( matcher.group( 2 ).trim() ); + id = matcher.group(1).trim(); + if (!(matcher.group(2) == null || matcher.group(2).trim().isEmpty())) { + layout = getLayout(matcher.group(2).trim()); } - repo = matcher.group( 3 ).trim(); + repo = matcher.group(3).trim(); } - return new MavenArtifactRepository( id, repo, layout, policy, policy ); + return new MavenArtifactRepository(id, repo, layout, policy, policy); } - private ArtifactRepositoryLayout getLayout( String id ) - throws MojoFailureException - { - ArtifactRepositoryLayout layout = repositoryLayouts.get( id ); + private ArtifactRepositoryLayout getLayout(String id) throws MojoFailureException { + ArtifactRepositoryLayout layout = repositoryLayouts.get(id); - if ( layout == null ) - { - throw new MojoFailureException( id, "Invalid repository layout", "Invalid repository layout: " + id ); + if (layout == null) { + throw new MojoFailureException(id, "Invalid repository layout", "Invalid repository layout: " + id); } return layout; diff --git a/src/main/java/org/apache/maven/plugins/dependency/PropertiesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/PropertiesMojo.java index 2961599db..54c0eeee6 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/PropertiesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/PropertiesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; @@ -38,17 +36,19 @@ * @author Paul Gier * @since 2.2 */ -//CHECKSTYLE_OFF: LineLength -@Mojo( name = "properties", requiresDependencyResolution = ResolutionScope.TEST, defaultPhase = LifecyclePhase.INITIALIZE, threadSafe = true ) -//CHECKSTYLE_ON: LineLength -public class PropertiesMojo - extends AbstractMojo -{ +// CHECKSTYLE_OFF: LineLength +@Mojo( + name = "properties", + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.INITIALIZE, + threadSafe = true) +// CHECKSTYLE_ON: LineLength +public class PropertiesMojo extends AbstractMojo { /** * The current Maven project */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** @@ -56,7 +56,7 @@ public class PropertiesMojo * * @since 2.7 */ - @Parameter( property = "mdep.skip", defaultValue = "false" ) + @Parameter(property = "mdep.skip", defaultValue = "false") private boolean skip; /** @@ -65,29 +65,26 @@ public class PropertiesMojo * @throws MojoExecutionException with a message if an error occurs. */ @Override - public void execute() - throws MojoExecutionException - { - if ( isSkip() ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException { + if (isSkip()) { + getLog().info("Skipping plugin execution"); return; } Set artifacts = project.getArtifacts(); - for ( Artifact artifact : artifacts ) - { - project.getProperties().setProperty( artifact.getDependencyConflictId(), - artifact.getFile().getAbsolutePath() ); + for (Artifact artifact : artifacts) { + project.getProperties() + .setProperty( + artifact.getDependencyConflictId(), + artifact.getFile().getAbsolutePath()); } } /** * @return {@link #skip} */ - public boolean isSkip() - { + public boolean isSkip() { return skip; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/PurgeLocalRepositoryMojo.java b/src/main/java/org/apache/maven/plugins/dependency/PurgeLocalRepositoryMojo.java index d76f06911..01be06394 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/PurgeLocalRepositoryMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/PurgeLocalRepositoryMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.io.File; import java.io.IOException; @@ -27,7 +26,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; @@ -72,10 +70,8 @@ * @author jdcasey * @since 2.0 */ -@Mojo( name = "purge-local-repository", threadSafe = true, requiresProject = false ) -public class PurgeLocalRepositoryMojo - extends AbstractMojo -{ +@Mojo(name = "purge-local-repository", threadSafe = true, requiresProject = false) +public class PurgeLocalRepositoryMojo extends AbstractMojo { private static final String VERSION_FUZZINESS = "version"; @@ -86,22 +82,22 @@ public class PurgeLocalRepositoryMojo /** * The Maven projects in the reactor. */ - @Parameter( defaultValue = "${reactorProjects}", readonly = true, required = true ) + @Parameter(defaultValue = "${reactorProjects}", readonly = true, required = true) private List reactorProjects; /** * The current Maven project. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; /** * This mojo execution, used to determine if it was launched from the lifecycle or the command-line. */ - @Parameter( defaultValue = "${mojo}", required = true, readonly = true ) + @Parameter(defaultValue = "${mojo}", required = true, readonly = true) private MojoExecution mojoExecution; /** @@ -128,7 +124,7 @@ public class PurgeLocalRepositoryMojo * * @since 2.6 */ - @Parameter( property = "manualInclude" ) + @Parameter(property = "manualInclude") private String manualInclude; /** @@ -146,7 +142,7 @@ public class PurgeLocalRepositoryMojo * * @since 2.6 */ - @Parameter( property = "include" ) + @Parameter(property = "include") private String include; /** @@ -160,20 +156,20 @@ public class PurgeLocalRepositoryMojo * deletion/refresh. This is a command-line alternative to the excludes parameter, since List * parameters are not currently compatible with CLI specification. */ - @Parameter( property = "exclude" ) + @Parameter(property = "exclude") private String exclude; /** * Whether to re-resolve the artifacts once they have been deleted from the local repository. If you are running * this mojo from the command-line, you may want to disable this. By default, artifacts will be re-resolved. */ - @Parameter( property = "reResolve", defaultValue = "true" ) + @Parameter(property = "reResolve", defaultValue = "true") private boolean reResolve; /** * The local repository, from which to delete artifacts. */ - @Parameter( defaultValue = "${localRepository}", readonly = true, required = true ) + @Parameter(defaultValue = "${localRepository}", readonly = true, required = true) private ArtifactRepository localRepository; /** @@ -197,19 +193,19 @@ public class PurgeLocalRepositoryMojo *
  • groupId - Eliminate all files associated with the artifact's groupId.
  • * */ - @Parameter( property = "resolutionFuzziness", defaultValue = "version" ) + @Parameter(property = "resolutionFuzziness", defaultValue = "version") private String resolutionFuzziness; /** * Whether this mojo should act on all transitive dependencies. Default value is true. */ - @Parameter( property = "actTransitively", defaultValue = "true" ) + @Parameter(property = "actTransitively", defaultValue = "true") private boolean actTransitively; /** * Whether this plugin should output verbose messages. Default is false. */ - @Parameter( property = "verbose", defaultValue = "false" ) + @Parameter(property = "verbose", defaultValue = "false") private boolean verbose; /** @@ -217,7 +213,7 @@ public class PurgeLocalRepositoryMojo * * @since 2.4 */ - @Parameter( property = "snapshotsOnly", defaultValue = "false" ) + @Parameter(property = "snapshotsOnly", defaultValue = "false") private boolean snapshotsOnly; /** @@ -225,15 +221,13 @@ public class PurgeLocalRepositoryMojo * * @since 2.7 */ - @Parameter( property = "skip", defaultValue = "false" ) + @Parameter(property = "skip", defaultValue = "false") private boolean skip; /** * Includes only direct project dependencies. */ - private class DirectDependencyFilter - extends AbstractFilter - { + private class DirectDependencyFilter extends AbstractFilter { private final Artifact projectArtifact; private final List directDependencies; @@ -243,24 +237,19 @@ private class DirectDependencyFilter * * @param directDependencies Set of dependencies objects which represent the direct dependencies of the project */ - DirectDependencyFilter( Artifact projectArtifact, List directDependencies ) - { + DirectDependencyFilter(Artifact projectArtifact, List directDependencies) { this.projectArtifact = projectArtifact; this.directDependencies = directDependencies; } @Override - public boolean accept( Node node, List parents ) - { + public boolean accept(Node node, List parents) { - if ( artifactsGAMatch( node, projectArtifact.getGroupId(), projectArtifact.getArtifactId() ) ) - { + if (artifactsGAMatch(node, projectArtifact.getGroupId(), projectArtifact.getArtifactId())) { return true; } - for ( Dependency dep : directDependencies ) - { - if ( this.artifactsGAMatch( node, dep.getGroupId(), dep.getArtifactId() ) ) - { + for (Dependency dep : directDependencies) { + if (this.artifactsGAMatch(node, dep.getGroupId(), dep.getArtifactId())) { return true; } } @@ -270,21 +259,17 @@ public boolean accept( Node node, List parents ) /* * Compare the groupId:artifactId of two artifacts. */ - private boolean artifactsGAMatch( Node node, String groupId, String artifactId ) - { - if ( node.getDependency() == null ) - { + private boolean artifactsGAMatch(Node node, String groupId, String artifactId) { + if (node.getDependency() == null) { return false; } - if ( !node.getDependency().getGroupId().equals( groupId ) ) - { - getLog().debug( "Different groupId: " + node.getDependency() + " " + groupId ); + if (!node.getDependency().getGroupId().equals(groupId)) { + getLog().debug("Different groupId: " + node.getDependency() + " " + groupId); return false; } - if ( !node.getDependency().getArtifactId().equals( artifactId ) ) - { - getLog().debug( "Different artifactId: " + node.getDependency() + " " + artifactId ); + if (!node.getDependency().getArtifactId().equals(artifactId)) { + getLog().debug("Different artifactId: " + node.getDependency() + " " + artifactId); return false; } return true; @@ -294,55 +279,40 @@ private boolean artifactsGAMatch( Node node, String groupId, String artifactId ) /** * Includes only snapshot artifacts */ - private static class SnapshotsFilter - extends AbstractFilter - { + private static class SnapshotsFilter extends AbstractFilter { @Override - public boolean accept( Node node, List parents ) - { - if ( node.getDependency() == null ) - { + public boolean accept(Node node, List parents) { + if (node.getDependency() == null) { return false; - } - else - { - return ArtifactUtils.isSnapshot( node.getDependency().getVersion() ); + } else { + return ArtifactUtils.isSnapshot(node.getDependency().getVersion()); } } } @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { + getLog().info("Skipping plugin execution"); return; } - if ( !StringUtils.isEmpty( manualInclude ) ) - { - manualIncludes = this.parseIncludes( manualInclude ); + if (!StringUtils.isEmpty(manualInclude)) { + manualIncludes = this.parseIncludes(manualInclude); } // If it's a manual purge, the only step is to delete from the local repo - if ( manualIncludes != null && manualIncludes.size() > 0 ) - { - manualPurge( manualIncludes ); + if (manualIncludes != null && manualIncludes.size() > 0) { + manualPurge(manualIncludes); return; } Set purgedArtifacts = new HashSet<>(); - if ( shouldPurgeAllProjectsInReactor() ) - { - for ( MavenProject reactorProject : reactorProjects ) - { - purgeLocalRepository( reactorProject, purgedArtifacts ); + if (shouldPurgeAllProjectsInReactor()) { + for (MavenProject reactorProject : reactorProjects) { + purgeLocalRepository(reactorProject, purgedArtifacts); } - } - else - { - purgeLocalRepository( project, purgedArtifacts ); + } else { + purgeLocalRepository(project, purgedArtifacts); } } @@ -352,8 +322,7 @@ public void execute() * * @return true if all projects in the reactor should be purged, false otherwise. */ - private boolean shouldPurgeAllProjectsInReactor() - { + private boolean shouldPurgeAllProjectsInReactor() { Source source = mojoExecution.getSource(); return reactorProjects.size() > 1 && source == Source.CLI; } @@ -365,36 +334,30 @@ private boolean shouldPurgeAllProjectsInReactor() * @param purgedArtifacts The artifacts that were already purged. * @throws MojoFailureException in case of errors during the purge. */ - private void purgeLocalRepository( MavenProject theProject, Set purgedArtifacts ) - throws MojoFailureException - { + private void purgeLocalRepository(MavenProject theProject, Set purgedArtifacts) + throws MojoFailureException { List dependencies = theProject.getDependencies(); - TransformableFilter dependencyFilter = createPurgeArtifactsFilter( theProject, dependencies, purgedArtifacts ); + TransformableFilter dependencyFilter = createPurgeArtifactsFilter(theProject, dependencies, purgedArtifacts); Set resolvedArtifactsToPurge = - getFilteredResolvedArtifacts( theProject, dependencies, dependencyFilter ); + getFilteredResolvedArtifacts(theProject, dependencies, dependencyFilter); - if ( resolvedArtifactsToPurge.isEmpty() ) - { - getLog().info( "No artifacts included for purge for project: " + getProjectKey( theProject ) ); + if (resolvedArtifactsToPurge.isEmpty()) { + getLog().info("No artifacts included for purge for project: " + getProjectKey(theProject)); return; } - purgeArtifacts( theProject, resolvedArtifactsToPurge ); - purgedArtifacts.addAll( resolvedArtifactsToPurge ); + purgeArtifacts(theProject, resolvedArtifactsToPurge); + purgedArtifacts.addAll(resolvedArtifactsToPurge); - if ( reResolve ) - { - getLog().info( "Re-resolving dependencies" ); - try - { - reResolveArtifacts( theProject, resolvedArtifactsToPurge ); - } - catch ( ArtifactResolutionException e ) - { + if (reResolve) { + getLog().info("Re-resolving dependencies"); + try { + reResolveArtifacts(theProject, resolvedArtifactsToPurge); + } catch (ArtifactResolutionException e) { String failureMessage = "Failed to refresh project dependencies for: " + theProject.getId(); - throw new MojoFailureException( failureMessage, e ); + throw new MojoFailureException(failureMessage, e); } } } @@ -405,49 +368,40 @@ private void purgeLocalRepository( MavenProject theProject, Set purged * @param theIncludes The includes. * @throws MojoExecutionException in case of an error. */ - private void manualPurge( List theIncludes ) - throws MojoExecutionException - { + private void manualPurge(List theIncludes) throws MojoExecutionException { MessageBuilder messageBuilder = MessageUtils.buffer(); - getLog().info( messageBuilder.a( "Deleting " ).strong( theIncludes.size() ) - .a( " manual " ) - .a( theIncludes.size() != 1 ? "dependencies" : "dependency" ) - .a( " from " ) - .strong( localRepository.getBasedir() ) - .toString() ); - - for ( String gavPattern : theIncludes ) - { - if ( StringUtils.isEmpty( gavPattern ) ) - { - getLog().debug( "Skipping empty gav pattern" ); + getLog().info(messageBuilder + .a("Deleting ") + .strong(theIncludes.size()) + .a(" manual ") + .a(theIncludes.size() != 1 ? "dependencies" : "dependency") + .a(" from ") + .strong(localRepository.getBasedir()) + .toString()); + + for (String gavPattern : theIncludes) { + if (StringUtils.isEmpty(gavPattern)) { + getLog().debug("Skipping empty gav pattern"); continue; } - String relativePath = gavToPath( gavPattern ); - if ( StringUtils.isEmpty( relativePath ) ) - { - getLog().debug( "Skipping empty relative path for gav pattern: " + gavPattern ); + String relativePath = gavToPath(gavPattern); + if (StringUtils.isEmpty(relativePath)) { + getLog().debug("Skipping empty relative path for gav pattern: " + gavPattern); continue; } - File purgeDir = new File( localRepository.getBasedir(), relativePath ); - if ( purgeDir.exists() ) - { - getLog().debug( "Deleting directory: " + purgeDir ); - try - { - FileUtils.deleteDirectory( purgeDir ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to purge directory: " + purgeDir ); + File purgeDir = new File(localRepository.getBasedir(), relativePath); + if (purgeDir.exists()) { + getLog().debug("Deleting directory: " + purgeDir); + try { + FileUtils.deleteDirectory(purgeDir); + } catch (IOException e) { + throw new MojoExecutionException("Unable to purge directory: " + purgeDir); } - } - else - { - getLog().debug( "Directory: " + purgeDir + " doesn't exist" ); + } else { + getLog().debug("Directory: " + purgeDir + " doesn't exist"); } } } @@ -458,20 +412,17 @@ private void manualPurge( List theIncludes ) * @param gav the groupId:artifactId:version string * @return the corresponding path */ - private String gavToPath( String gav ) - { - if ( StringUtils.isEmpty( gav ) ) - { + private String gavToPath(String gav) { + if (StringUtils.isEmpty(gav)) { return null; } - String[] pathComponents = gav.split( ":" ); + String[] pathComponents = gav.split(":"); - StringBuilder path = new StringBuilder( pathComponents[0].replace( '.', '/' ) ); + StringBuilder path = new StringBuilder(pathComponents[0].replace('.', '/')); - for ( int i = 1; i < pathComponents.length; ++i ) - { - path.append( "/" ).append( pathComponents[i] ); + for (int i = 1; i < pathComponents.length; ++i) { + path.append("/").append(pathComponents[i]); } return path.toString(); @@ -486,57 +437,48 @@ private String gavToPath( String gav ) * @param purgedArtifacts The artifacts already purged. * @return the created filter */ - private TransformableFilter createPurgeArtifactsFilter( MavenProject theProject, List dependencies, - Set purgedArtifacts ) - { + private TransformableFilter createPurgeArtifactsFilter( + MavenProject theProject, List dependencies, Set purgedArtifacts) { List subFilters = new ArrayList<>(); // System dependencies should never be purged - subFilters.add( ScopeFilter.excluding( Artifact.SCOPE_SYSTEM ) ); + subFilters.add(ScopeFilter.excluding(Artifact.SCOPE_SYSTEM)); - if ( this.snapshotsOnly ) - { - subFilters.add( new SnapshotsFilter() ); + if (this.snapshotsOnly) { + subFilters.add(new SnapshotsFilter()); } // The CLI includes/excludes overrides configuration in the pom - if ( !StringUtils.isEmpty( this.include ) ) - { - this.includes = parseIncludes( this.include ); + if (!StringUtils.isEmpty(this.include)) { + this.includes = parseIncludes(this.include); } - if ( this.includes != null ) - { - subFilters.add( new PatternInclusionsFilter( includes ) ); + if (this.includes != null) { + subFilters.add(new PatternInclusionsFilter(includes)); } - if ( !StringUtils.isEmpty( this.exclude ) ) - { - this.excludes = parseIncludes( this.exclude ); + if (!StringUtils.isEmpty(this.exclude)) { + this.excludes = parseIncludes(this.exclude); } - if ( this.excludes != null ) - { - subFilters.add( new PatternExclusionsFilter( excludes ) ); + if (this.excludes != null) { + subFilters.add(new PatternExclusionsFilter(excludes)); } - if ( !actTransitively ) - { - subFilters.add( new DirectDependencyFilter( theProject.getArtifact(), dependencies ) ); + if (!actTransitively) { + subFilters.add(new DirectDependencyFilter(theProject.getArtifact(), dependencies)); } - List exclusions = new ArrayList<>( reactorProjects.size() ); + List exclusions = new ArrayList<>(reactorProjects.size()); // It doesn't make sense to include projects from the reactor here since they're likely not able to be resolved - for ( MavenProject reactorProject : reactorProjects ) - { - exclusions.add( toPatternExcludes( reactorProject.getArtifact() ) ); + for (MavenProject reactorProject : reactorProjects) { + exclusions.add(toPatternExcludes(reactorProject.getArtifact())); } // There is no need to consider a second time artifacts that were already purged (re-resolved or not) - for ( Artifact purgedArtifact : purgedArtifacts ) - { - exclusions.add( toPatternExcludes( purgedArtifact ) ); + for (Artifact purgedArtifact : purgedArtifacts) { + exclusions.add(toPatternExcludes(purgedArtifact)); } - subFilters.add( new PatternExclusionsFilter( exclusions ) ); + subFilters.add(new PatternExclusionsFilter(exclusions)); - return new AndFilter( subFilters ); + return new AndFilter(subFilters); } /** @@ -545,10 +487,9 @@ private TransformableFilter createPurgeArtifactsFilter( MavenProject theProject, * @param artifact Artifact. * @return String representation of a pattern for an exclude filter for the given artifact. */ - private String toPatternExcludes( Artifact artifact ) - { + private String toPatternExcludes(Artifact artifact) { return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" - + artifact.getArtifactHandler().getExtension() + ":" + artifact.getVersion(); + + artifact.getArtifactHandler().getExtension() + ":" + artifact.getVersion(); } /** @@ -557,184 +498,155 @@ private String toPatternExcludes( Artifact artifact ) * @param theInclude The list of includes * @return the includes list */ - private List parseIncludes( String theInclude ) - { + private List parseIncludes(String theInclude) { List theIncludes = new ArrayList<>(); - if ( theInclude != null ) - { - String[] elements = theInclude.split( "," ); - theIncludes.addAll( Arrays.asList( elements ) ); + if (theInclude != null) { + String[] elements = theInclude.split(","); + theIncludes.addAll(Arrays.asList(elements)); } return theIncludes; } - private Set getFilteredResolvedArtifacts( MavenProject theProject, List dependencies, - TransformableFilter filter ) - { - try - { - Iterable results = - dependencyResolver.resolveDependencies( session.getProjectBuildingRequest(), theProject.getModel(), - filter ); + private Set getFilteredResolvedArtifacts( + MavenProject theProject, List dependencies, TransformableFilter filter) { + try { + Iterable results = dependencyResolver.resolveDependencies( + session.getProjectBuildingRequest(), theProject.getModel(), filter); Set resolvedArtifacts = new LinkedHashSet<>(); - for ( ArtifactResult artResult : results ) - { - resolvedArtifacts.add( artResult.getArtifact() ); + for (ArtifactResult artResult : results) { + resolvedArtifacts.add(artResult.getArtifact()); } return resolvedArtifacts; - } - catch ( DependencyResolverException e ) - { - getLog().info( "Unable to resolve all dependencies for: " + getProjectKey( theProject ) - + ". Falling back to non-transitive mode for initial artifact resolution." ); + } catch (DependencyResolverException e) { + getLog().info("Unable to resolve all dependencies for: " + getProjectKey(theProject) + + ". Falling back to non-transitive mode for initial artifact resolution."); } Set resolvedArtifacts = new LinkedHashSet<>(); - ArtifactFilter artifactFilter = filter.transform( new ArtifactIncludeFilterTransformer() ); + ArtifactFilter artifactFilter = filter.transform(new ArtifactIncludeFilterTransformer()); - for ( Dependency dependency : dependencies ) - { + for (Dependency dependency : dependencies) { DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); - coordinate.setGroupId( dependency.getGroupId() ); - coordinate.setArtifactId( dependency.getArtifactId() ); - coordinate.setVersion( dependency.getVersion() ); - coordinate.setExtension( artifactHandlerManager.getArtifactHandler( dependency.getType() ).getExtension() ); - try - { - Artifact artifact = - artifactResolver.resolveArtifact( session.getProjectBuildingRequest(), coordinate ).getArtifact(); - if ( artifactFilter.include( artifact ) ) - { - resolvedArtifacts.add( artifact ); + coordinate.setGroupId(dependency.getGroupId()); + coordinate.setArtifactId(dependency.getArtifactId()); + coordinate.setVersion(dependency.getVersion()); + coordinate.setExtension(artifactHandlerManager + .getArtifactHandler(dependency.getType()) + .getExtension()); + try { + Artifact artifact = artifactResolver + .resolveArtifact(session.getProjectBuildingRequest(), coordinate) + .getArtifact(); + if (artifactFilter.include(artifact)) { + resolvedArtifacts.add(artifact); } - } - catch ( ArtifactResolverException e ) - { - getLog().debug( "Unable to resolve artifact: " + coordinate ); + } catch (ArtifactResolverException e) { + getLog().debug("Unable to resolve artifact: " + coordinate); } } return resolvedArtifacts; } - private void purgeArtifacts( MavenProject theProject, Set artifacts ) - { + private void purgeArtifacts(MavenProject theProject, Set artifacts) { MessageBuilder messageBuilder = MessageUtils.buffer(); - getLog().info( messageBuilder.a( "Deleting " ).strong( artifacts.size() ) - .a( " " ).strong( actTransitively ? "transitive" : "direct" ) - .a( artifacts.size() != 1 ? " dependencies" : " dependency" ) - .a( " for project " ).strong( getProjectKey( theProject ) ) - .a( " from " ).strong( localRepository.getBasedir() ) - .a( " with artifact " ).strong( resolutionFuzziness ).a( " resolution fuzziness" ) - .toString() ); - - for ( Artifact artifact : artifacts ) - { - verbose( "Purging artifact: " + artifact.getId() ); - - File deleteTarget = findDeleteTarget( artifact ); - - verbose( "Deleting: " + deleteTarget ); - - if ( deleteTarget.isDirectory() ) - { - try - { - FileUtils.deleteDirectory( deleteTarget ); - } - catch ( IOException e ) - { - getLog().warn( "Unable to purge local repository location: " + deleteTarget, e ); + getLog().info(messageBuilder + .a("Deleting ") + .strong(artifacts.size()) + .a(" ") + .strong(actTransitively ? "transitive" : "direct") + .a(artifacts.size() != 1 ? " dependencies" : " dependency") + .a(" for project ") + .strong(getProjectKey(theProject)) + .a(" from ") + .strong(localRepository.getBasedir()) + .a(" with artifact ") + .strong(resolutionFuzziness) + .a(" resolution fuzziness") + .toString()); + + for (Artifact artifact : artifacts) { + verbose("Purging artifact: " + artifact.getId()); + + File deleteTarget = findDeleteTarget(artifact); + + verbose("Deleting: " + deleteTarget); + + if (deleteTarget.isDirectory()) { + try { + FileUtils.deleteDirectory(deleteTarget); + } catch (IOException e) { + getLog().warn("Unable to purge local repository location: " + deleteTarget, e); } - } - else - { - if ( !deleteTarget.delete() ) - { + } else { + if (!deleteTarget.delete()) { deleteTarget.deleteOnExit(); - getLog().warn( "Unable to purge local repository location immediately: " + deleteTarget ); + getLog().warn("Unable to purge local repository location immediately: " + deleteTarget); } } - artifact.setResolved( false ); + artifact.setResolved(false); } } - private void reResolveArtifacts( MavenProject theProject, Set artifacts ) - throws ArtifactResolutionException - { + private void reResolveArtifacts(MavenProject theProject, Set artifacts) + throws ArtifactResolutionException { // Always need to re-resolve the poms in case they were purged along with the artifact // because Maven 2 will not automatically re-resolve them when resolving the artifact - for ( Artifact artifact : artifacts ) - { - verbose( "Resolving artifact: " + artifact.getId() ); - - try - { - //CHECKSTYLE_OFF: LineLength - artifactResolver.resolveArtifact( session.getProjectBuildingRequest(), - TransferUtils.toArtifactCoordinate( artifact ) ); - //CHECKSTYLE_ON: LineLength - } - catch ( ArtifactResolverException e ) - { - verbose( e.getMessage() ); + for (Artifact artifact : artifacts) { + verbose("Resolving artifact: " + artifact.getId()); + + try { + // CHECKSTYLE_OFF: LineLength + artifactResolver.resolveArtifact( + session.getProjectBuildingRequest(), TransferUtils.toArtifactCoordinate(artifact)); + // CHECKSTYLE_ON: LineLength + } catch (ArtifactResolverException e) { + verbose(e.getMessage()); } } List missingArtifacts = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { - try - { - artifactResolver.resolveArtifact( session.getProjectBuildingRequest(), artifact ); - } - catch ( ArtifactResolverException e ) - { - verbose( e.getMessage() ); - missingArtifacts.add( artifact ); + for (Artifact artifact : artifacts) { + try { + artifactResolver.resolveArtifact(session.getProjectBuildingRequest(), artifact); + } catch (ArtifactResolverException e) { + verbose(e.getMessage()); + missingArtifacts.add(artifact); } } - if ( missingArtifacts.size() > 0 ) - { - StringBuilder message = new StringBuilder( "required artifacts missing:" ); - message.append( System.lineSeparator() ); - for ( Artifact missingArtifact : missingArtifacts ) - { - message.append( " " ).append( missingArtifact.getId() ).append( System.lineSeparator() ); + if (missingArtifacts.size() > 0) { + StringBuilder message = new StringBuilder("required artifacts missing:"); + message.append(System.lineSeparator()); + for (Artifact missingArtifact : missingArtifacts) { + message.append(" ").append(missingArtifact.getId()).append(System.lineSeparator()); } - message.append( System.lineSeparator() ); - message.append( "for the artifact:" ); + message.append(System.lineSeparator()); + message.append("for the artifact:"); - throw new ArtifactResolutionException( message.toString(), theProject.getArtifact(), - theProject.getRemoteArtifactRepositories() ); + throw new ArtifactResolutionException( + message.toString(), theProject.getArtifact(), theProject.getRemoteArtifactRepositories()); } } - private File findDeleteTarget( Artifact artifact ) - { + private File findDeleteTarget(Artifact artifact) { // Use localRepository.pathOf() in case artifact.getFile() is not set - File deleteTarget = new File( localRepository.getBasedir(), localRepository.pathOf( artifact ) ); + File deleteTarget = new File(localRepository.getBasedir(), localRepository.pathOf(artifact)); - if ( GROUP_ID_FUZZINESS.equals( resolutionFuzziness ) ) - { + if (GROUP_ID_FUZZINESS.equals(resolutionFuzziness)) { // get the groupId dir. deleteTarget = deleteTarget.getParentFile().getParentFile().getParentFile(); - } - else if ( ARTIFACT_ID_FUZZINESS.equals( resolutionFuzziness ) ) - { + } else if (ARTIFACT_ID_FUZZINESS.equals(resolutionFuzziness)) { // get the artifactId dir. deleteTarget = deleteTarget.getParentFile().getParentFile(); - } - else if ( VERSION_FUZZINESS.equals( resolutionFuzziness ) ) - { + } else if (VERSION_FUZZINESS.equals(resolutionFuzziness)) { // get the version dir. deleteTarget = deleteTarget.getParentFile(); } @@ -742,32 +654,27 @@ else if ( VERSION_FUZZINESS.equals( resolutionFuzziness ) ) return deleteTarget; } - private void verbose( String message ) - { - if ( verbose || getLog().isDebugEnabled() ) - { - getLog().info( message ); + private void verbose(String message) { + if (verbose || getLog().isDebugEnabled()) { + getLog().info(message); } } - private String getProjectKey( MavenProject project ) - { + private String getProjectKey(MavenProject project) { return project.getArtifactId(); } /** * @return {@link #skip} */ - public boolean isSkip() - { + public boolean isSkip() { return skip; } /** * @param skip {@link #skip} */ - public void setSkip( boolean skip ) - { + public void setSkip(boolean skip) { this.skip = skip; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java index e069bd464..00186de95 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import java.io.File; import java.io.StringWriter; @@ -29,7 +28,6 @@ import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; @@ -55,10 +53,7 @@ * @author Mark Hobson * @since 2.0-alpha-5 */ -public abstract class AbstractAnalyzeMojo - extends AbstractMojo - implements Contextualizable -{ +public abstract class AbstractAnalyzeMojo extends AbstractMojo implements Contextualizable { // fields ----------------------------------------------------------------- /** @@ -70,7 +65,7 @@ public abstract class AbstractAnalyzeMojo /** * The Maven project to analyze. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** @@ -81,19 +76,19 @@ public abstract class AbstractAnalyzeMojo * * @since 2.2 */ - @Parameter( property = "analyzer", defaultValue = "default" ) + @Parameter(property = "analyzer", defaultValue = "default") private String analyzer; /** * Whether to fail the build if a dependency warning is found. */ - @Parameter( property = "failOnWarning", defaultValue = "false" ) + @Parameter(property = "failOnWarning", defaultValue = "false") private boolean failOnWarning; /** * Output used dependencies. */ - @Parameter( property = "verbose", defaultValue = "false" ) + @Parameter(property = "verbose", defaultValue = "false") private boolean verbose; /** @@ -101,7 +96,7 @@ public abstract class AbstractAnalyzeMojo * * Non-test scoped list will be not affected. */ - @Parameter( property = "ignoreNonCompile", defaultValue = "false" ) + @Parameter(property = "ignoreNonCompile", defaultValue = "false") private boolean ignoreNonCompile; /** @@ -109,7 +104,7 @@ public abstract class AbstractAnalyzeMojo * * @since 3.2.0 */ - @Parameter( property = "ignoreUnusedRuntime", defaultValue = "false" ) + @Parameter(property = "ignoreUnusedRuntime", defaultValue = "false") private boolean ignoreUnusedRuntime; /** @@ -120,7 +115,7 @@ public abstract class AbstractAnalyzeMojo * * @since 3.3.1-SNAPSHOT */ - @Parameter( property = "ignoreAllNonTestScoped", defaultValue = "false" ) + @Parameter(property = "ignoreAllNonTestScoped", defaultValue = "false") private boolean ignoreAllNonTestScoped; /** @@ -128,7 +123,7 @@ public abstract class AbstractAnalyzeMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "outputXML", defaultValue = "false" ) + @Parameter(property = "outputXML", defaultValue = "false") private boolean outputXML; /** @@ -136,7 +131,7 @@ public abstract class AbstractAnalyzeMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "scriptableOutput", defaultValue = "false" ) + @Parameter(property = "scriptableOutput", defaultValue = "false") private boolean scriptableOutput; /** @@ -144,7 +139,7 @@ public abstract class AbstractAnalyzeMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "scriptableFlag", defaultValue = "$$$%%%" ) + @Parameter(property = "scriptableFlag", defaultValue = "$$$%%%") private String scriptableFlag; /** @@ -152,7 +147,7 @@ public abstract class AbstractAnalyzeMojo * * @since 2.0-alpha-5 */ - @Parameter( defaultValue = "${basedir}", readonly = true ) + @Parameter(defaultValue = "${basedir}", readonly = true) private File baseDir; /** @@ -160,7 +155,7 @@ public abstract class AbstractAnalyzeMojo * * @since 2.0-alpha-5 */ - @Parameter( defaultValue = "${project.build.directory}", readonly = true ) + @Parameter(defaultValue = "${project.build.directory}", readonly = true) private File outputDirectory; /** @@ -177,7 +172,7 @@ public abstract class AbstractAnalyzeMojo * * @since 2.7 */ - @Parameter( property = "mdep.analyze.skip", defaultValue = "false" ) + @Parameter(property = "mdep.analyze.skip", defaultValue = "false") private boolean skip; /** @@ -268,7 +263,7 @@ public abstract class AbstractAnalyzeMojo // defaultValue value on @Parameter - not work with Maven 3.2.5 // When is set defaultValue always win, and there is no possibility to override by plugin configuration. @Parameter - private List ignoredPackagings = Arrays.asList( "pom", "ear" ); + private List ignoredPackagings = Arrays.asList("pom", "ear"); // Mojo methods ----------------------------------------------------------- @@ -276,32 +271,26 @@ public abstract class AbstractAnalyzeMojo * @see org.apache.maven.plugin.Mojo#execute() */ @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { + getLog().info("Skipping plugin execution"); return; } - if ( ignoredPackagings.contains( project.getPackaging() ) ) - { - getLog().info( "Skipping " + project.getPackaging() + " project" ); + if (ignoredPackagings.contains(project.getPackaging())) { + getLog().info("Skipping " + project.getPackaging() + " project"); return; } - if ( outputDirectory == null || !outputDirectory.exists() ) - { - getLog().info( "Skipping project with no build directory" ); + if (outputDirectory == null || !outputDirectory.exists()) { + getLog().info("Skipping project with no build directory"); return; } boolean warning = checkDependencies(); - if ( warning && failOnWarning ) - { - throw new MojoExecutionException( "Dependency problems found" ); + if (warning && failOnWarning) { + throw new MojoExecutionException("Dependency problems found"); } } @@ -309,344 +298,277 @@ public void execute() * @return {@link ProjectDependencyAnalyzer} * @throws MojoExecutionException in case of an error. */ - protected ProjectDependencyAnalyzer createProjectDependencyAnalyzer() - throws MojoExecutionException - { - try - { - final PlexusContainer container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); - return container.lookup( ProjectDependencyAnalyzer.class, analyzer ); - } - catch ( Exception exception ) - { - throw new MojoExecutionException( "Failed to instantiate ProjectDependencyAnalyser" - + " / role-hint " + analyzer, exception ); + protected ProjectDependencyAnalyzer createProjectDependencyAnalyzer() throws MojoExecutionException { + try { + final PlexusContainer container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); + return container.lookup(ProjectDependencyAnalyzer.class, analyzer); + } catch (Exception exception) { + throw new MojoExecutionException( + "Failed to instantiate ProjectDependencyAnalyser" + " / role-hint " + analyzer, exception); } } @Override - public void contextualize( Context theContext ) - { + public void contextualize(Context theContext) { this.context = theContext; } /** * @return {@link #skip} */ - protected final boolean isSkip() - { + protected final boolean isSkip() { return skip; } // private methods -------------------------------------------------------- - private boolean checkDependencies() - throws MojoExecutionException - { + private boolean checkDependencies() throws MojoExecutionException { ProjectDependencyAnalysis analysis; - try - { - analysis = createProjectDependencyAnalyzer().analyze( project ); + try { + analysis = createProjectDependencyAnalyzer().analyze(project); - if ( usedDependencies != null ) - { - analysis = analysis.forceDeclaredDependenciesUsage( usedDependencies ); + if (usedDependencies != null) { + analysis = analysis.forceDeclaredDependenciesUsage(usedDependencies); } - } - catch ( ProjectDependencyAnalyzerException exception ) - { - throw new MojoExecutionException( "Cannot analyze dependencies", exception ); + } catch (ProjectDependencyAnalyzerException exception) { + throw new MojoExecutionException("Cannot analyze dependencies", exception); } - if ( ignoreNonCompile ) - { + if (ignoreNonCompile) { analysis = analysis.ignoreNonCompile(); } - Set usedDeclared = new LinkedHashSet<>( analysis.getUsedDeclaredArtifacts() ); + Set usedDeclared = new LinkedHashSet<>(analysis.getUsedDeclaredArtifacts()); Map> usedUndeclaredWithClasses = - new LinkedHashMap<>( analysis.getUsedUndeclaredArtifactsWithClasses() ); - Set unusedDeclared = new LinkedHashSet<>( analysis.getUnusedDeclaredArtifacts() ); - Set nonTestScope = new LinkedHashSet<>( analysis.getTestArtifactsWithNonTestScope() ); + new LinkedHashMap<>(analysis.getUsedUndeclaredArtifactsWithClasses()); + Set unusedDeclared = new LinkedHashSet<>(analysis.getUnusedDeclaredArtifacts()); + Set nonTestScope = new LinkedHashSet<>(analysis.getTestArtifactsWithNonTestScope()); Set ignoredUsedUndeclared = new LinkedHashSet<>(); Set ignoredUnusedDeclared = new LinkedHashSet<>(); Set ignoredNonTestScope = new LinkedHashSet<>(); - if ( ignoreUnusedRuntime ) - { - filterArtifactsByScope( unusedDeclared, Artifact.SCOPE_RUNTIME ); + if (ignoreUnusedRuntime) { + filterArtifactsByScope(unusedDeclared, Artifact.SCOPE_RUNTIME); } - ignoredUsedUndeclared.addAll( filterDependencies( usedUndeclaredWithClasses.keySet(), ignoredDependencies ) ); - ignoredUsedUndeclared.addAll( filterDependencies( usedUndeclaredWithClasses.keySet(), - ignoredUsedUndeclaredDependencies ) ); + ignoredUsedUndeclared.addAll(filterDependencies(usedUndeclaredWithClasses.keySet(), ignoredDependencies)); + ignoredUsedUndeclared.addAll( + filterDependencies(usedUndeclaredWithClasses.keySet(), ignoredUsedUndeclaredDependencies)); - ignoredUnusedDeclared.addAll( filterDependencies( unusedDeclared, ignoredDependencies ) ); - ignoredUnusedDeclared.addAll( filterDependencies( unusedDeclared, ignoredUnusedDeclaredDependencies ) ); + ignoredUnusedDeclared.addAll(filterDependencies(unusedDeclared, ignoredDependencies)); + ignoredUnusedDeclared.addAll(filterDependencies(unusedDeclared, ignoredUnusedDeclaredDependencies)); - if ( ignoreAllNonTestScoped ) - { - ignoredNonTestScope.addAll( filterDependencies ( nonTestScope, new String [] { "*" } ) ); - } - else - { - ignoredNonTestScope.addAll( filterDependencies( nonTestScope, ignoredDependencies ) ); - ignoredNonTestScope.addAll( filterDependencies( nonTestScope, ignoredNonTestScopedDependencies ) ); + if (ignoreAllNonTestScoped) { + ignoredNonTestScope.addAll(filterDependencies(nonTestScope, new String[] {"*"})); + } else { + ignoredNonTestScope.addAll(filterDependencies(nonTestScope, ignoredDependencies)); + ignoredNonTestScope.addAll(filterDependencies(nonTestScope, ignoredNonTestScopedDependencies)); } boolean reported = false; boolean warning = false; - if ( verbose && !usedDeclared.isEmpty() ) - { - getLog().info( "Used declared dependencies found:" ); + if (verbose && !usedDeclared.isEmpty()) { + getLog().info("Used declared dependencies found:"); - logArtifacts( analysis.getUsedDeclaredArtifacts(), false ); + logArtifacts(analysis.getUsedDeclaredArtifacts(), false); reported = true; } - if ( !usedUndeclaredWithClasses.isEmpty() ) - { - logDependencyWarning( "Used undeclared dependencies found:" ); + if (!usedUndeclaredWithClasses.isEmpty()) { + logDependencyWarning("Used undeclared dependencies found:"); - if ( verbose ) - { - logArtifacts( usedUndeclaredWithClasses, true ); - } - else - { - logArtifacts( usedUndeclaredWithClasses.keySet(), true ); + if (verbose) { + logArtifacts(usedUndeclaredWithClasses, true); + } else { + logArtifacts(usedUndeclaredWithClasses.keySet(), true); } reported = true; warning = true; } - if ( !unusedDeclared.isEmpty() ) - { - logDependencyWarning( "Unused declared dependencies found:" ); + if (!unusedDeclared.isEmpty()) { + logDependencyWarning("Unused declared dependencies found:"); - logArtifacts( unusedDeclared, true ); + logArtifacts(unusedDeclared, true); reported = true; warning = true; } - if ( !nonTestScope.isEmpty() ) - { - logDependencyWarning( "Non-test scoped test only dependencies found:" ); + if (!nonTestScope.isEmpty()) { + logDependencyWarning("Non-test scoped test only dependencies found:"); - logArtifacts( nonTestScope, true ); + logArtifacts(nonTestScope, true); reported = true; warning = true; } - if ( verbose && !ignoredUsedUndeclared.isEmpty() ) - { - getLog().info( "Ignored used undeclared dependencies:" ); + if (verbose && !ignoredUsedUndeclared.isEmpty()) { + getLog().info("Ignored used undeclared dependencies:"); - logArtifacts( ignoredUsedUndeclared, false ); + logArtifacts(ignoredUsedUndeclared, false); reported = true; } - if ( verbose && !ignoredUnusedDeclared.isEmpty() ) - { - getLog().info( "Ignored unused declared dependencies:" ); + if (verbose && !ignoredUnusedDeclared.isEmpty()) { + getLog().info("Ignored unused declared dependencies:"); - logArtifacts( ignoredUnusedDeclared, false ); + logArtifacts(ignoredUnusedDeclared, false); reported = true; } - if ( verbose && !ignoredNonTestScope.isEmpty() ) - { - getLog().info( "Ignored non-test scoped test only dependencies:" ); + if (verbose && !ignoredNonTestScope.isEmpty()) { + getLog().info("Ignored non-test scoped test only dependencies:"); - logArtifacts( ignoredNonTestScope, false ); + logArtifacts(ignoredNonTestScope, false); reported = true; } - if ( outputXML ) - { - writeDependencyXML( usedUndeclaredWithClasses.keySet() ); + if (outputXML) { + writeDependencyXML(usedUndeclaredWithClasses.keySet()); } - if ( scriptableOutput ) - { - writeScriptableOutput( usedUndeclaredWithClasses.keySet() ); + if (scriptableOutput) { + writeScriptableOutput(usedUndeclaredWithClasses.keySet()); } - if ( !reported ) - { - getLog().info( "No dependency problems found" ); + if (!reported) { + getLog().info("No dependency problems found"); } return warning; } - private void filterArtifactsByScope( Set artifacts, String scope ) - { - artifacts.removeIf( artifact -> artifact.getScope().equals( scope ) ); + private void filterArtifactsByScope(Set artifacts, String scope) { + artifacts.removeIf(artifact -> artifact.getScope().equals(scope)); } - private void logArtifacts( Set artifacts, boolean warn ) - { - if ( artifacts.isEmpty() ) - { - getLog().info( " None" ); - } - else - { - for ( Artifact artifact : artifacts ) - { + private void logArtifacts(Set artifacts, boolean warn) { + if (artifacts.isEmpty()) { + getLog().info(" None"); + } else { + for (Artifact artifact : artifacts) { // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961 artifact.isSnapshot(); - if ( warn ) - { - logDependencyWarning( " " + artifact ); - } - else - { - getLog().info( " " + artifact ); + if (warn) { + logDependencyWarning(" " + artifact); + } else { + getLog().info(" " + artifact); } - } } } - private void logArtifacts( Map> artifacts, boolean warn ) - { - if ( artifacts.isEmpty() ) - { - getLog().info( " None" ); - } - else - { - for ( Map.Entry> entry : artifacts.entrySet() ) - { + private void logArtifacts(Map> artifacts, boolean warn) { + if (artifacts.isEmpty()) { + getLog().info(" None"); + } else { + for (Map.Entry> entry : artifacts.entrySet()) { // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961 entry.getKey().isSnapshot(); - if ( warn ) - { - logDependencyWarning( " " + entry.getKey() ); - for ( String clazz : entry.getValue() ) - { - logDependencyWarning( " class " + clazz ); + if (warn) { + logDependencyWarning(" " + entry.getKey()); + for (String clazz : entry.getValue()) { + logDependencyWarning(" class " + clazz); } - } - else - { - getLog().info( " " + entry.getKey() ); - for ( String clazz : entry.getValue() ) - { - getLog().info( " class " + clazz ); + } else { + getLog().info(" " + entry.getKey()); + for (String clazz : entry.getValue()) { + getLog().info(" class " + clazz); } } - } } } - private void logDependencyWarning( CharSequence content ) - { - if ( failOnWarning ) - { - getLog().error( content ); - } - else - { - getLog().warn( content ); + private void logDependencyWarning(CharSequence content) { + if (failOnWarning) { + getLog().error(content); + } else { + getLog().warn(content); } } - private void writeDependencyXML( Set artifacts ) - { - if ( !artifacts.isEmpty() ) - { - getLog().info( "Add the following to your pom to correct the missing dependencies: " ); + private void writeDependencyXML(Set artifacts) { + if (!artifacts.isEmpty()) { + getLog().info("Add the following to your pom to correct the missing dependencies: "); StringWriter out = new StringWriter(); - PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter( out ); + PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter(out); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961 artifact.isSnapshot(); - writer.startElement( "dependency" ); - writer.startElement( "groupId" ); - writer.writeText( artifact.getGroupId() ); + writer.startElement("dependency"); + writer.startElement("groupId"); + writer.writeText(artifact.getGroupId()); writer.endElement(); - writer.startElement( "artifactId" ); - writer.writeText( artifact.getArtifactId() ); + writer.startElement("artifactId"); + writer.writeText(artifact.getArtifactId()); writer.endElement(); - writer.startElement( "version" ); - writer.writeText( artifact.getBaseVersion() ); - if ( !StringUtils.isBlank( artifact.getClassifier() ) ) - { - writer.startElement( "classifier" ); - writer.writeText( artifact.getClassifier() ); + writer.startElement("version"); + writer.writeText(artifact.getBaseVersion()); + if (!StringUtils.isBlank(artifact.getClassifier())) { + writer.startElement("classifier"); + writer.writeText(artifact.getClassifier()); writer.endElement(); } writer.endElement(); - if ( !Artifact.SCOPE_COMPILE.equals( artifact.getScope() ) ) - { - writer.startElement( "scope" ); - writer.writeText( artifact.getScope() ); + if (!Artifact.SCOPE_COMPILE.equals(artifact.getScope())) { + writer.startElement("scope"); + writer.writeText(artifact.getScope()); writer.endElement(); } writer.endElement(); } - getLog().info( System.lineSeparator() + out.getBuffer() ); + getLog().info(System.lineSeparator() + out.getBuffer()); } } - private void writeScriptableOutput( Set artifacts ) - { - if ( !artifacts.isEmpty() ) - { - getLog().info( "Missing dependencies: " ); + private void writeScriptableOutput(Set artifacts) { + if (!artifacts.isEmpty()) { + getLog().info("Missing dependencies: "); String pomFile = baseDir.getAbsolutePath() + File.separatorChar + "pom.xml"; StringBuilder buf = new StringBuilder(); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961 artifact.isSnapshot(); - //CHECKSTYLE_OFF: LineLength - buf.append( scriptableFlag ) - .append( ":" ) - .append( pomFile ) - .append( ":" ) - .append( artifact.getDependencyConflictId() ) - .append( ":" ) - .append( artifact.getClassifier() ) - .append( ":" ) - .append( artifact.getBaseVersion() ) - .append( ":" ) - .append( artifact.getScope() ) - .append( System.lineSeparator() ); - //CHECKSTYLE_ON: LineLength + // CHECKSTYLE_OFF: LineLength + buf.append(scriptableFlag) + .append(":") + .append(pomFile) + .append(":") + .append(artifact.getDependencyConflictId()) + .append(":") + .append(artifact.getClassifier()) + .append(":") + .append(artifact.getBaseVersion()) + .append(":") + .append(artifact.getScope()) + .append(System.lineSeparator()); + // CHECKSTYLE_ON: LineLength } - getLog().info( System.lineSeparator() + buf ); + getLog().info(System.lineSeparator() + buf); } } - private List filterDependencies( Set artifacts, String[] excludes ) - { - ArtifactFilter filter = new StrictPatternExcludesArtifactFilter( Arrays.asList( excludes ) ); + private List filterDependencies(Set artifacts, String[] excludes) { + ArtifactFilter filter = new StrictPatternExcludesArtifactFilter(Arrays.asList(excludes)); List result = new ArrayList<>(); - for ( Iterator it = artifacts.iterator(); it.hasNext(); ) - { + for (Iterator it = artifacts.iterator(); it.hasNext(); ) { Artifact artifact = it.next(); - if ( !filter.include( artifact ) ) - { + if (!filter.include(artifact)) { it.remove(); - result.add( artifact ); + result.add(artifact); } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java index cdc7b963e..afb52f999 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import java.util.Collections; import java.util.HashMap; @@ -26,7 +25,6 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; @@ -48,28 +46,26 @@ * @author Brian Fox * @since 2.0-alpha-3 */ -@Mojo( name = "analyze-dep-mgt", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -public class AnalyzeDepMgt - extends AbstractMojo -{ +@Mojo(name = "analyze-dep-mgt", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +public class AnalyzeDepMgt extends AbstractMojo { // fields ----------------------------------------------------------------- /** * */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * Fail the build if a problem is detected. */ - @Parameter( property = "mdep.analyze.failBuild", defaultValue = "false" ) + @Parameter(property = "mdep.analyze.failBuild", defaultValue = "false") private boolean failBuild = false; /** * Ignore Direct Dependency Overrides of dependencyManagement section. */ - @Parameter( property = "mdep.analyze.ignore.direct", defaultValue = "true" ) + @Parameter(property = "mdep.analyze.ignore.direct", defaultValue = "true") private boolean ignoreDirect = true; /** @@ -77,7 +73,7 @@ public class AnalyzeDepMgt * * @since 2.7 */ - @Parameter( property = "mdep.analyze.skip", defaultValue = "false" ) + @Parameter(property = "mdep.analyze.skip", defaultValue = "false") private boolean skip; // Mojo methods ----------------------------------------------------------- @@ -86,26 +82,19 @@ public class AnalyzeDepMgt * @see org.apache.maven.plugin.Mojo#execute() */ @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("Skipping plugin execution"); return; } boolean result = checkDependencyManagement(); - if ( result ) - { - if ( this.failBuild ) + if (result) { + if (this.failBuild) { - { - throw new MojoExecutionException( "Found Dependency errors." ); - } - else - { - getLog().warn( "Potential problems found in Dependency Management " ); + throw new MojoExecutionException("Found Dependency errors."); + } else { + getLog().warn("Potential problems found in Dependency Management "); } } } @@ -116,71 +105,60 @@ public void execute() * @return true if errors are found. * @throws MojoExecutionException */ - private boolean checkDependencyManagement() - throws MojoExecutionException - { + private boolean checkDependencyManagement() throws MojoExecutionException { boolean foundError = false; - getLog().info( "Found Resolved Dependency/DependencyManagement mismatches:" ); + getLog().info("Found Resolved Dependency/DependencyManagement mismatches:"); List depMgtDependencies = null; DependencyManagement depMgt = project.getDependencyManagement(); - if ( depMgt != null ) - { + if (depMgt != null) { depMgtDependencies = depMgt.getDependencies(); } - if ( depMgtDependencies != null && !depMgtDependencies.isEmpty() ) - { + if (depMgtDependencies != null && !depMgtDependencies.isEmpty()) { // put all the dependencies from depMgt into a map for quick lookup Map depMgtMap = new HashMap<>(); Map exclusions = new HashMap<>(); - for ( Dependency depMgtDependency : depMgtDependencies ) - { - depMgtMap.put( depMgtDependency.getManagementKey(), depMgtDependency ); + for (Dependency depMgtDependency : depMgtDependencies) { + depMgtMap.put(depMgtDependency.getManagementKey(), depMgtDependency); // now put all the exclusions into a map for quick lookup - exclusions.putAll( addExclusions( depMgtDependency.getExclusions() ) ); + exclusions.putAll(addExclusions(depMgtDependency.getExclusions())); } // get dependencies for the project (including transitive) - Set allDependencyArtifacts = new LinkedHashSet<>( project.getArtifacts() ); + Set allDependencyArtifacts = new LinkedHashSet<>(project.getArtifacts()); // don't warn if a dependency that is directly listed overrides // depMgt. That's ok. - if ( this.ignoreDirect ) - { - getLog().info( "\tIgnoring Direct Dependencies." ); + if (this.ignoreDirect) { + getLog().info("\tIgnoring Direct Dependencies."); Set directDependencies = project.getDependencyArtifacts(); - allDependencyArtifacts.removeAll( directDependencies ); + allDependencyArtifacts.removeAll(directDependencies); } // log exclusion errors - List exclusionErrors = getExclusionErrors( exclusions, allDependencyArtifacts ); - for ( Artifact exclusion : exclusionErrors ) - { - getLog().info( StringUtils.stripEnd( getArtifactManagementKey( exclusion ), ":" ) - + " was excluded in DepMgt, but version " + exclusion.getVersion() - + " has been found in the dependency tree." ); + List exclusionErrors = getExclusionErrors(exclusions, allDependencyArtifacts); + for (Artifact exclusion : exclusionErrors) { + getLog().info(StringUtils.stripEnd(getArtifactManagementKey(exclusion), ":") + + " was excluded in DepMgt, but version " + exclusion.getVersion() + + " has been found in the dependency tree."); foundError = true; } // find and log version mismatches - Map mismatch = getMismatch( depMgtMap, allDependencyArtifacts ); - for ( Map.Entry entry : mismatch.entrySet() ) - { - logMismatch( entry.getKey(), entry.getValue() ); + Map mismatch = getMismatch(depMgtMap, allDependencyArtifacts); + for (Map.Entry entry : mismatch.entrySet()) { + logMismatch(entry.getKey(), entry.getValue()); foundError = true; } - if ( !foundError ) - { - getLog().info( "\tNone" ); + if (!foundError) { + getLog().info("\tNone"); } - } - else - { - getLog().info( "\tNothing in DepMgt." ); + } else { + getLog().info("\tNothing in DepMgt."); } return foundError; @@ -192,12 +170,9 @@ private boolean checkDependencyManagement() * @param exclusionList to be added to the map. * @return a map of the exclusions using the Dependency ManagementKey as the keyset. */ - public Map addExclusions( List exclusionList ) - { - if ( exclusionList != null ) - { - return exclusionList.stream() - .collect( Collectors.toMap( this::getExclusionKey, exclusion -> exclusion ) ); + public Map addExclusions(List exclusionList) { + if (exclusionList != null) { + return exclusionList.stream().collect(Collectors.toMap(this::getExclusionKey, exclusion -> exclusion)); } return Collections.emptyMap(); } @@ -210,19 +185,17 @@ public Map addExclusions( List exclusionList ) * @param allDependencyArtifacts resolved artifacts to be compared. * @return list of artifacts that should have been excluded. */ - public List getExclusionErrors( Map exclusions, Set allDependencyArtifacts ) - { + public List getExclusionErrors(Map exclusions, Set allDependencyArtifacts) { return allDependencyArtifacts.stream() - .filter( artifact -> exclusions.containsKey( getExclusionKey( artifact ) ) ) - .collect( Collectors.toList( ) ); + .filter(artifact -> exclusions.containsKey(getExclusionKey(artifact))) + .collect(Collectors.toList()); } /** * @param artifact {@link Artifact} * @return The resulting GA. */ - public String getExclusionKey( Artifact artifact ) - { + public String getExclusionKey(Artifact artifact) { return artifact.getGroupId() + ":" + artifact.getArtifactId(); } @@ -230,8 +203,7 @@ public String getExclusionKey( Artifact artifact ) * @param ex The exclusion key. * @return The resulting combination of groupId+artifactId. */ - public String getExclusionKey( Exclusion ex ) - { + public String getExclusionKey(Exclusion ex) { return ex.getGroupId() + ":" + ex.getArtifactId(); } @@ -242,23 +214,19 @@ public String getExclusionKey( Exclusion ex ) * @param allDependencyArtifacts contains the set of all artifacts to compare. * @return a map containing the resolved artifact as the key and the listed dependency as the value. */ - public Map getMismatch( Map depMgtMap, - Set allDependencyArtifacts ) - { + public Map getMismatch( + Map depMgtMap, Set allDependencyArtifacts) { Map mismatchMap = new HashMap<>(); - for ( Artifact dependencyArtifact : allDependencyArtifacts ) - { - Dependency depFromDepMgt = depMgtMap.get( getArtifactManagementKey( dependencyArtifact ) ); - if ( depFromDepMgt != null ) - { + for (Artifact dependencyArtifact : allDependencyArtifacts) { + Dependency depFromDepMgt = depMgtMap.get(getArtifactManagementKey(dependencyArtifact)); + if (depFromDepMgt != null) { // workaround for MNG-2961 dependencyArtifact.isSnapshot(); - if ( depFromDepMgt.getVersion() != null - && !depFromDepMgt.getVersion().equals( dependencyArtifact.getBaseVersion() ) ) - { - mismatchMap.put( dependencyArtifact, depFromDepMgt ); + if (depFromDepMgt.getVersion() != null + && !depFromDepMgt.getVersion().equals(dependencyArtifact.getBaseVersion())) { + mismatchMap.put(dependencyArtifact, depFromDepMgt); } } } @@ -273,18 +241,16 @@ public Map getMismatch( Map depMgtMap, * @param dependencyFromDepMgt the dependency listed in the DependencyManagement section. * @throws MojoExecutionException in case of errors. */ - public void logMismatch( Artifact dependencyArtifact, Dependency dependencyFromDepMgt ) - throws MojoExecutionException - { - if ( dependencyArtifact == null || dependencyFromDepMgt == null ) - { - throw new MojoExecutionException( "Invalid params: Artifact: " + dependencyArtifact + " Dependency: " - + dependencyFromDepMgt ); + public void logMismatch(Artifact dependencyArtifact, Dependency dependencyFromDepMgt) + throws MojoExecutionException { + if (dependencyArtifact == null || dependencyFromDepMgt == null) { + throw new MojoExecutionException( + "Invalid params: Artifact: " + dependencyArtifact + " Dependency: " + dependencyFromDepMgt); } - getLog().info( "\tDependency: " + StringUtils.stripEnd( dependencyFromDepMgt.getManagementKey(), ":" ) ); - getLog().info( "\t\tDepMgt : " + dependencyFromDepMgt.getVersion() ); - getLog().info( "\t\tResolved: " + dependencyArtifact.getBaseVersion() ); + getLog().info("\tDependency: " + StringUtils.stripEnd(dependencyFromDepMgt.getManagementKey(), ":")); + getLog().info("\t\tDepMgt : " + dependencyFromDepMgt.getVersion()); + getLog().info("\t\tResolved: " + dependencyArtifact.getBaseVersion()); } /** @@ -293,57 +259,50 @@ public void logMismatch( Artifact dependencyArtifact, Dependency dependencyFromD * @param artifact to gen the key for * @return a string in the form: groupId:ArtifactId:Type[:Classifier] */ - public String getArtifactManagementKey( Artifact artifact ) - { + public String getArtifactManagementKey(Artifact artifact) { return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getType() - + ( ( artifact.getClassifier() != null ) ? ":" + artifact.getClassifier() : "" ); + + ((artifact.getClassifier() != null) ? ":" + artifact.getClassifier() : ""); } /** * @return the failBuild */ - protected final boolean isFailBuild() - { + protected final boolean isFailBuild() { return this.failBuild; } /** * @param theFailBuild the failBuild to set */ - public void setFailBuild( boolean theFailBuild ) - { + public void setFailBuild(boolean theFailBuild) { this.failBuild = theFailBuild; } /** * @return the project */ - protected final MavenProject getProject() - { + protected final MavenProject getProject() { return this.project; } /** * @param theProject the project to set */ - public void setProject( MavenProject theProject ) - { + public void setProject(MavenProject theProject) { this.project = theProject; } /** * @return the ignoreDirect */ - protected final boolean isIgnoreDirect() - { + protected final boolean isIgnoreDirect() { return this.ignoreDirect; } /** * @param theIgnoreDirect the ignoreDirect to set */ - public void setIgnoreDirect( boolean theIgnoreDirect ) - { + public void setIgnoreDirect(boolean theIgnoreDirect) { this.ignoreDirect = theIgnoreDirect; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDuplicateMojo.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDuplicateMojo.java index 552f4981d..fe6aa8728 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDuplicateMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDuplicateMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import java.io.IOException; import java.io.Reader; @@ -27,7 +26,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; @@ -47,119 +45,99 @@ * * @author Vincent Siveton */ -@Mojo( name = "analyze-duplicate", aggregator = false, threadSafe = true ) -public class AnalyzeDuplicateMojo - extends AbstractMojo -{ +@Mojo(name = "analyze-duplicate", aggregator = false, threadSafe = true) +public class AnalyzeDuplicateMojo extends AbstractMojo { public static final String MESSAGE_DUPLICATE_DEP_IN_DEPENDENCIES = - "List of duplicate dependencies defined in in your pom.xml:\n"; + "List of duplicate dependencies defined in in your pom.xml:\n"; public static final String MESSAGE_DUPLICATE_DEP_IN_DEPMGMT = - "List of duplicate dependencies defined in in your pom.xml:\n"; + "List of duplicate dependencies defined in in your pom.xml:\n"; /** * Skip plugin execution completely. * * @since 2.7 */ - @Parameter( property = "mdep.analyze.skip", defaultValue = "false" ) + @Parameter(property = "mdep.analyze.skip", defaultValue = "false") private boolean skip; /** * The Maven project to analyze. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * {@inheritDoc} */ @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("Skipping plugin execution"); return; } MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model; - try ( Reader reader = ReaderFactory.newXmlReader( project.getFile() ) ) - { - model = pomReader.read( reader ); - } - catch ( IOException | XmlPullParserException e ) - { - throw new MojoExecutionException( "Exception: " + e.getMessage(), e ); + try (Reader reader = ReaderFactory.newXmlReader(project.getFile())) { + model = pomReader.read(reader); + } catch (IOException | XmlPullParserException e) { + throw new MojoExecutionException("Exception: " + e.getMessage(), e); } Set duplicateDependencies = Collections.emptySet(); - if ( model.getDependencies() != null ) - { - duplicateDependencies = findDuplicateDependencies( model.getDependencies() ); + if (model.getDependencies() != null) { + duplicateDependencies = findDuplicateDependencies(model.getDependencies()); } Set duplicateDependenciesManagement = Collections.emptySet(); - if ( model.getDependencyManagement() != null && model.getDependencyManagement().getDependencies() != null ) - { + if (model.getDependencyManagement() != null + && model.getDependencyManagement().getDependencies() != null) { duplicateDependenciesManagement = - findDuplicateDependencies( model.getDependencyManagement().getDependencies() ); + findDuplicateDependencies(model.getDependencyManagement().getDependencies()); } - if ( getLog().isInfoEnabled() ) - { + if (getLog().isInfoEnabled()) { StringBuilder sb = new StringBuilder(); - createMessage( duplicateDependencies, sb, MESSAGE_DUPLICATE_DEP_IN_DEPENDENCIES ); - createMessage( duplicateDependenciesManagement, sb, MESSAGE_DUPLICATE_DEP_IN_DEPMGMT ); + createMessage(duplicateDependencies, sb, MESSAGE_DUPLICATE_DEP_IN_DEPENDENCIES); + createMessage(duplicateDependenciesManagement, sb, MESSAGE_DUPLICATE_DEP_IN_DEPMGMT); - if ( sb.length() > 0 ) - { - getLog().info( sb.toString() ); - } - else - { - getLog().info( "No duplicate dependencies found in or in " ); + if (sb.length() > 0) { + getLog().info(sb.toString()); + } else { + getLog().info("No duplicate dependencies found in or in "); } } } - private void createMessage( Set duplicateDependencies, StringBuilder sb, - String messageDuplicateDepInDependencies ) - { - if ( !duplicateDependencies.isEmpty() ) - { - if ( sb.length() > 0 ) - { - sb.append( "\n" ); + private void createMessage( + Set duplicateDependencies, StringBuilder sb, String messageDuplicateDepInDependencies) { + if (!duplicateDependencies.isEmpty()) { + if (sb.length() > 0) { + sb.append("\n"); } - sb.append( messageDuplicateDepInDependencies ); - for ( Iterator it = duplicateDependencies.iterator(); it.hasNext(); ) - { + sb.append(messageDuplicateDepInDependencies); + for (Iterator it = duplicateDependencies.iterator(); it.hasNext(); ) { String dup = it.next(); - sb.append( "\to " ).append( dup ); - if ( it.hasNext() ) - { - sb.append( "\n" ); + sb.append("\to ").append(dup); + if (it.hasNext()) { + sb.append("\n"); } } } } - private Set findDuplicateDependencies( List modelDependencies ) - { + private Set findDuplicateDependencies(List modelDependencies) { List modelDependencies2 = new ArrayList<>(); - for ( Dependency dep : modelDependencies ) - { - modelDependencies2.add( dep.getManagementKey() ); + for (Dependency dep : modelDependencies) { + modelDependencies2.add(dep.getManagementKey()); } // @formatter:off return new LinkedHashSet<>( - CollectionUtils.disjunction( modelDependencies2, new LinkedHashSet<>( modelDependencies2 ) ) ); + CollectionUtils.disjunction(modelDependencies2, new LinkedHashSet<>(modelDependencies2))); // @formatter:on } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojo.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojo.java index 2bd434144..84907bb60 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -38,10 +37,8 @@ * @see AnalyzeOnlyMojo * @since 2.0-alpha-3 */ -@Mojo( name = "analyze", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -@Execute( phase = LifecyclePhase.TEST_COMPILE ) -public class AnalyzeMojo - extends AbstractAnalyzeMojo -{ +@Mojo(name = "analyze", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +@Execute(phase = LifecyclePhase.TEST_COMPILE) +public class AnalyzeMojo extends AbstractAnalyzeMojo { // subclassed to provide annotations } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeOnlyMojo.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeOnlyMojo.java index 0265661d3..43d1e3021 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeOnlyMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeOnlyMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; @@ -38,16 +37,13 @@ * @see AnalyzeMojo * @since 2.0 */ -//@formatter:off -@Mojo( - name = "analyze-only", - requiresDependencyResolution = ResolutionScope.TEST, - defaultPhase = LifecyclePhase.VERIFY, - threadSafe = true -) -//@formatter:on -public class AnalyzeOnlyMojo - extends AbstractAnalyzeMojo -{ +// @formatter:off +@Mojo( + name = "analyze-only", + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.VERIFY, + threadSafe = true) +// @formatter:on +public class AnalyzeOnlyMojo extends AbstractAnalyzeMojo { // subclassed to provide annotations } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportMojo.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportMojo.java index fd51491f3..5e3e40fa3 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; +import java.util.Locale; +import java.util.ResourceBundle; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Execute; @@ -32,20 +33,15 @@ import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalyzer; import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalyzerException; -import java.util.Locale; -import java.util.ResourceBundle; - /** * Analyzes the dependencies of this project and produces a report that summarizes which are: used and declared; used * and undeclared; unused and declared. * * @since 2.0-alpha-5 */ -@Mojo( name = "analyze-report", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -@Execute( phase = LifecyclePhase.TEST_COMPILE ) -public class AnalyzeReportMojo - extends AbstractMavenReport -{ +@Mojo(name = "analyze-report", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +@Execute(phase = LifecyclePhase.TEST_COMPILE) +public class AnalyzeReportMojo extends AbstractMavenReport { // fields ----------------------------------------------------------------- /** @@ -59,7 +55,7 @@ public class AnalyzeReportMojo * * @since 2.2 */ - @Parameter( property = "ignoreNonCompile", defaultValue = "false" ) + @Parameter(property = "ignoreNonCompile", defaultValue = "false") private boolean ignoreNonCompile; /** @@ -76,7 +72,7 @@ public class AnalyzeReportMojo * * @since 2.7 */ - @Parameter( property = "mdep.analyze.skip", defaultValue = "false" ) + @Parameter(property = "mdep.analyze.skip", defaultValue = "false") private boolean skip; // Mojo methods ----------------------------------------------------------- @@ -85,56 +81,45 @@ public class AnalyzeReportMojo * @see org.apache.maven.plugin.Mojo#execute() */ @Override - public void executeReport( Locale locale ) - throws MavenReportException - { + public void executeReport(Locale locale) throws MavenReportException { // Step 1: Analyze the project ProjectDependencyAnalysis analysis; - try - { - analysis = analyzer.analyze( project ); + try { + analysis = analyzer.analyze(project); - if ( usedDependencies != null ) - { - analysis = analysis.forceDeclaredDependenciesUsage( usedDependencies ); + if (usedDependencies != null) { + analysis = analysis.forceDeclaredDependenciesUsage(usedDependencies); } - } - catch ( ProjectDependencyAnalyzerException exception ) - { - throw new MavenReportException( "Cannot analyze dependencies", exception ); + } catch (ProjectDependencyAnalyzerException exception) { + throw new MavenReportException("Cannot analyze dependencies", exception); } // remove everything that's not in the compile scope - if ( ignoreNonCompile ) - { + if (ignoreNonCompile) { analysis = analysis.ignoreNonCompile(); } // Step 2: Create sink and bundle Sink sink = getSink(); - ResourceBundle bundle = getBundle( locale ); + ResourceBundle bundle = getBundle(locale); // Step 3: Generate the report AnalyzeReportView analyzethis = new AnalyzeReportView(); - analyzethis.generateReport( analysis, sink, bundle ); + analyzethis.generateReport(analysis, sink, bundle); } // MavenReport methods ---------------------------------------------------- - @Override - public boolean canGenerateReport() - { - if ( skip ) - { - getLog().info( "Skipping plugin execution" ); + public boolean canGenerateReport() { + if (skip) { + getLog().info("Skipping plugin execution"); return false; } // Step 0: Checking pom availability - if ( "pom".equals( project.getPackaging() ) ) - { - getLog().info( "Skipping pom project" ); + if ("pom".equals(project.getPackaging())) { + getLog().info("Skipping pom project"); return false; } @@ -145,8 +130,7 @@ public boolean canGenerateReport() * @see org.apache.maven.reporting.AbstractMavenReport#getOutputName() */ @Override - public String getOutputName() - { + public String getOutputName() { return "dependency-analysis"; } @@ -154,18 +138,16 @@ public String getOutputName() * @see org.apache.maven.reporting.AbstractMavenReport#getName(java.util.Locale) */ @Override - public String getName( Locale locale ) - { - return getBundle( locale ).getString( "analyze.report.name" ); + public String getName(Locale locale) { + return getBundle(locale).getString("analyze.report.name"); } /* * @see org.apache.maven.reporting.AbstractMavenReport#getDescription(java.util.Locale) */ @Override - public String getDescription( Locale locale ) - { - return getBundle( locale ).getString( "analyze.report.description" ); + public String getDescription(Locale locale) { + return getBundle(locale).getString("analyze.report.description"); } // protected methods ------------------------------------------------------ @@ -174,8 +156,8 @@ public String getDescription( Locale locale ) * @param locale the current locale * @return The resource bundle {@link ResourceBundle} */ - protected ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "analyze-report", locale, this.getClass().getClassLoader() ); + protected ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle( + "analyze-report", locale, this.getClass().getClassLoader()); } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportView.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportView.java index 571be741b..4bcc3d47e 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportView.java +++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportView.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import java.util.Iterator; import java.util.ResourceBundle; - import org.apache.maven.artifact.Artifact; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalysis; @@ -30,20 +28,18 @@ * This is the view part of the analyze-report mojo. It generates the HTML report for the project website. The HTML * output is same as the CLI output. */ -public class AnalyzeReportView -{ +public class AnalyzeReportView { /** * Generates the HTML report. - * + * * @param analysis {@link ProjectDependencyAnalysis} * @param sink {@link Sink} * @param bundle {@link ResourceBundle} */ - public void generateReport( ProjectDependencyAnalysis analysis, Sink sink, ResourceBundle bundle ) - { + public void generateReport(ProjectDependencyAnalysis analysis, Sink sink, ResourceBundle bundle) { sink.head(); sink.title(); - sink.text( bundle.getString( "analyze.report.header" ) ); + sink.text(bundle.getString("analyze.report.header")); sink.title_(); sink.head_(); sink.body(); @@ -51,78 +47,69 @@ public void generateReport( ProjectDependencyAnalysis analysis, Sink sink, Resou // Generate title sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "analyze.report.mainTitle" ) ); + sink.text(bundle.getString("analyze.report.mainTitle")); sink.sectionTitle1_(); // Generate Used Declared dependencies: sink.section2(); sink.sectionTitle2(); - sink.text( bundle.getString( "analyze.report.UsedDeclaredDependencies" ) ); + sink.text(bundle.getString("analyze.report.UsedDeclaredDependencies")); sink.sectionTitle2_(); - if ( analysis.getUsedDeclaredArtifacts().isEmpty() ) - { + if (analysis.getUsedDeclaredArtifacts().isEmpty()) { sink.paragraph(); - sink.text( bundle.getString( "analyze.report.noDependency" ) ); + sink.text(bundle.getString("analyze.report.noDependency")); sink.paragraph_(); sink.horizontalRule(); - } - else - { - generateDependenciesTable( sink, analysis.getUsedDeclaredArtifacts().iterator() ); + } else { + generateDependenciesTable(sink, analysis.getUsedDeclaredArtifacts().iterator()); } sink.section2_(); // Generate Used Undeclared dependencies: sink.section2(); sink.sectionTitle2(); - sink.text( bundle.getString( "analyze.report.UsedUndeclaredDependencies" ) ); + sink.text(bundle.getString("analyze.report.UsedUndeclaredDependencies")); sink.sectionTitle2_(); - if ( analysis.getUsedUndeclaredArtifacts().isEmpty() ) - { + if (analysis.getUsedUndeclaredArtifacts().isEmpty()) { sink.paragraph(); - sink.text( bundle.getString( "analyze.report.noDependency" ) ); + sink.text(bundle.getString("analyze.report.noDependency")); sink.paragraph_(); sink.horizontalRule(); - } - else - { - generateDependenciesTable( sink, analysis.getUsedUndeclaredArtifacts().iterator() ); + } else { + generateDependenciesTable( + sink, analysis.getUsedUndeclaredArtifacts().iterator()); } sink.section2_(); // Generate Unused declared dependencies: sink.section2(); sink.sectionTitle2(); - sink.text( bundle.getString( "analyze.report.UnusedDeclaredDependencies" ) ); + sink.text(bundle.getString("analyze.report.UnusedDeclaredDependencies")); sink.sectionTitle2_(); - if ( analysis.getUnusedDeclaredArtifacts().isEmpty() ) - { + if (analysis.getUnusedDeclaredArtifacts().isEmpty()) { sink.paragraph(); - sink.text( bundle.getString( "analyze.report.noDependency" ) ); + sink.text(bundle.getString("analyze.report.noDependency")); sink.paragraph_(); sink.horizontalRule(); - } - else - { - generateDependenciesTable( sink, analysis.getUnusedDeclaredArtifacts().iterator() ); + } else { + generateDependenciesTable( + sink, analysis.getUnusedDeclaredArtifacts().iterator()); } sink.section2_(); // Generate Non-Test Scoped Test Dependencies: sink.section2(); sink.sectionTitle2(); - sink.text( "Compile Scoped Test Dependencies" ); + sink.text("Compile Scoped Test Dependencies"); sink.sectionTitle2_(); - if ( analysis.getTestArtifactsWithNonTestScope().isEmpty() ) - { + if (analysis.getTestArtifactsWithNonTestScope().isEmpty()) { sink.paragraph(); - sink.text( "None" ); + sink.text("None"); sink.paragraph_(); sink.horizontalRule(); - } - else - { - generateDependenciesTable( sink, analysis.getTestArtifactsWithNonTestScope().iterator() ); + } else { + generateDependenciesTable( + sink, analysis.getTestArtifactsWithNonTestScope().iterator()); } sink.section2_(); @@ -136,89 +123,84 @@ public void generateReport( ProjectDependencyAnalysis analysis, Sink sink, Resou /** * Generate a table for the given dependencies iterator. - * + * * @param sink {@link Sink} * @param iter {@link Artifact} */ - public void generateDependenciesTable( Sink sink, Iterator iter ) - { + public void generateDependenciesTable(Sink sink, Iterator iter) { sink.table(); sink.tableRow(); sink.tableCell(); sink.bold(); - sink.text( "GroupId" ); + sink.text("GroupId"); sink.bold_(); sink.tableCell_(); sink.tableCell(); sink.bold(); - sink.text( "ArtifactId" ); + sink.text("ArtifactId"); sink.bold_(); sink.tableCell_(); sink.tableCell(); sink.bold(); - sink.text( "Version" ); + sink.text("Version"); sink.bold_(); sink.tableCell_(); sink.tableCell(); sink.bold(); - sink.text( "Scope" ); + sink.text("Scope"); sink.bold_(); sink.tableCell_(); sink.tableCell(); sink.bold(); - sink.text( "Classifier" ); + sink.text("Classifier"); sink.bold_(); sink.tableCell_(); sink.tableCell(); sink.bold(); - sink.text( "Type" ); + sink.text("Type"); sink.bold_(); sink.tableCell_(); sink.tableCell(); sink.bold(); - sink.text( "Optional" ); + sink.text("Optional"); sink.bold_(); sink.tableCell_(); sink.tableRow_(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); sink.tableRow(); sink.tableCell(); - sink.text( artifact.getGroupId() ); + sink.text(artifact.getGroupId()); sink.tableCell_(); sink.tableCell(); - sink.text( artifact.getArtifactId() ); + sink.text(artifact.getArtifactId()); sink.tableCell_(); sink.tableCell(); - sink.text( artifact.getVersion() ); + sink.text(artifact.getVersion()); sink.tableCell_(); sink.tableCell(); - sink.text( artifact.getScope() ); + sink.text(artifact.getScope()); sink.tableCell_(); sink.tableCell(); - sink.text( artifact.getClassifier() ); + sink.text(artifact.getClassifier()); sink.tableCell_(); sink.tableCell(); - sink.text( artifact.getType() ); + sink.text(artifact.getType()); sink.tableCell_(); sink.tableCell(); - if ( artifact.isOptional() ) - { - sink.text( "" ); - } - else - { - sink.text( "false" ); + if (artifact.isOptional()) { + sink.text(""); + } else { + sink.text("false"); } sink.tableCell_(); diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java index eed762196..6e6dd5271 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Objects; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; @@ -51,15 +49,13 @@ * @author Brian Fox * @see ArtifactItem */ -public abstract class AbstractFromConfigurationMojo - extends AbstractDependencyMojo -{ +public abstract class AbstractFromConfigurationMojo extends AbstractDependencyMojo { /** * Default output location used for mojo, unless overridden in ArtifactItem. * * @since 1.0 */ - @Parameter( property = "outputDirectory", defaultValue = "${project.build.directory}/dependency" ) + @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}/dependency") private File outputDirectory; /** @@ -67,7 +63,7 @@ public abstract class AbstractFromConfigurationMojo * * @since 1.0 */ - @Parameter( property = "mdep.overWriteReleases", defaultValue = "false" ) + @Parameter(property = "mdep.overWriteReleases", defaultValue = "false") private boolean overWriteReleases; /** @@ -75,7 +71,7 @@ public abstract class AbstractFromConfigurationMojo * * @since 1.0 */ - @Parameter( property = "mdep.overWriteSnapshots", defaultValue = "false" ) + @Parameter(property = "mdep.overWriteSnapshots", defaultValue = "false") private boolean overWriteSnapshots; /** @@ -83,7 +79,7 @@ public abstract class AbstractFromConfigurationMojo * * @since 2.0 */ - @Parameter( property = "mdep.overIfNewer", defaultValue = "true" ) + @Parameter(property = "mdep.overIfNewer", defaultValue = "true") private boolean overWriteIfNewer; /** @@ -113,19 +109,16 @@ public abstract class AbstractFromConfigurationMojo @Component private ArtifactHandlerManager artifactHandlerManager; - abstract ArtifactItemFilter getMarkedArtifactFilter( ArtifactItem item ); + abstract ArtifactItemFilter getMarkedArtifactFilter(ArtifactItem item); /** * artifactItems is filled by either field injection or by setArtifact(). - * + * * @throws MojoFailureException in case of an error. */ - protected void verifyRequirements() - throws MojoFailureException - { - if ( artifactItems == null || artifactItems.isEmpty() ) - { - throw new MojoFailureException( "Either artifact or artifactItems is required " ); + protected void verifyRequirements() throws MojoFailureException { + if (artifactItems == null || artifactItems.isEmpty()) { + throw new MojoFailureException("Either artifact or artifactItems is required "); } } @@ -138,63 +131,51 @@ protected void verifyRequirements() * @throws MojoExecutionException with a message if an error occurs. * @see ArtifactItem */ - protected List getProcessedArtifactItems( ProcessArtifactItemsRequest processArtifactItemsRequest ) - throws MojoExecutionException - { + protected List getProcessedArtifactItems(ProcessArtifactItemsRequest processArtifactItemsRequest) + throws MojoExecutionException { boolean removeVersion = processArtifactItemsRequest.isRemoveVersion(), - prependGroupId = processArtifactItemsRequest.isPrependGroupId(), - useBaseVersion = processArtifactItemsRequest.isUseBaseVersion(); + prependGroupId = processArtifactItemsRequest.isPrependGroupId(), + useBaseVersion = processArtifactItemsRequest.isUseBaseVersion(); boolean removeClassifier = processArtifactItemsRequest.isRemoveClassifier(); - if ( artifactItems == null || artifactItems.size() < 1 ) - { - throw new MojoExecutionException( "There are no artifactItems configured." ); + if (artifactItems == null || artifactItems.size() < 1) { + throw new MojoExecutionException("There are no artifactItems configured."); } - for ( ArtifactItem artifactItem : artifactItems ) - { - this.getLog().info( "Configured Artifact: " + artifactItem.toString() ); + for (ArtifactItem artifactItem : artifactItems) { + this.getLog().info("Configured Artifact: " + artifactItem.toString()); - if ( artifactItem.getOutputDirectory() == null ) - { - artifactItem.setOutputDirectory( this.outputDirectory ); + if (artifactItem.getOutputDirectory() == null) { + artifactItem.setOutputDirectory(this.outputDirectory); } artifactItem.getOutputDirectory().mkdirs(); // make sure we have a version. - if ( StringUtils.isEmpty( artifactItem.getVersion() ) ) - { - fillMissingArtifactVersion( artifactItem ); + if (StringUtils.isEmpty(artifactItem.getVersion())) { + fillMissingArtifactVersion(artifactItem); } - artifactItem.setArtifact( this.getArtifact( artifactItem ) ); + artifactItem.setArtifact(this.getArtifact(artifactItem)); - if ( StringUtils.isEmpty( artifactItem.getDestFileName() ) ) - { - artifactItem.setDestFileName( DependencyUtil.getFormattedFileName( artifactItem.getArtifact(), - removeVersion, prependGroupId, - useBaseVersion, removeClassifier ) ); + if (StringUtils.isEmpty(artifactItem.getDestFileName())) { + artifactItem.setDestFileName(DependencyUtil.getFormattedFileName( + artifactItem.getArtifact(), removeVersion, prependGroupId, useBaseVersion, removeClassifier)); } - try - { - artifactItem.setNeedsProcessing( checkIfProcessingNeeded( artifactItem ) ); - } - catch ( ArtifactFilterException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + artifactItem.setNeedsProcessing(checkIfProcessingNeeded(artifactItem)); + } catch (ArtifactFilterException e) { + throw new MojoExecutionException(e.getMessage(), e); } } return artifactItems; } - private boolean checkIfProcessingNeeded( ArtifactItem item ) - throws MojoExecutionException, ArtifactFilterException - { - return StringUtils.equalsIgnoreCase( item.getOverWrite(), "true" ) - || getMarkedArtifactFilter( item ).isArtifactIncluded( item ); + private boolean checkIfProcessingNeeded(ArtifactItem item) throws MojoExecutionException, ArtifactFilterException { + return StringUtils.equalsIgnoreCase(item.getOverWrite(), "true") + || getMarkedArtifactFilter(item).isArtifactIncluded(item); } /** @@ -205,13 +186,10 @@ private boolean checkIfProcessingNeeded( ArtifactItem item ) * @return Artifact object representing the specified file. * @throws MojoExecutionException with a message if the version can't be found in DependencyManagement. */ - protected Artifact getArtifact( ArtifactItem artifactItem ) - throws MojoExecutionException - { + protected Artifact getArtifact(ArtifactItem artifactItem) throws MojoExecutionException { Artifact artifact; - try - { + try { // mdep-50 - rolledback for now because it's breaking some functionality. /* * List listeners = new ArrayList(); Set theSet = new HashSet(); theSet.add( artifact ); @@ -224,36 +202,32 @@ protected Artifact getArtifact( ArtifactItem artifactItem ) ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); - if ( localRepositoryDirectory != null ) - { + if (localRepositoryDirectory != null) { buildingRequest = - repositoryManager.setLocalRepositoryBasedir( buildingRequest, localRepositoryDirectory ); + repositoryManager.setLocalRepositoryBasedir(buildingRequest, localRepositoryDirectory); } // Map dependency to artifact coordinate DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); - coordinate.setGroupId( artifactItem.getGroupId() ); - coordinate.setArtifactId( artifactItem.getArtifactId() ); - coordinate.setVersion( artifactItem.getVersion() ); - coordinate.setClassifier( artifactItem.getClassifier() ); + coordinate.setGroupId(artifactItem.getGroupId()); + coordinate.setArtifactId(artifactItem.getArtifactId()); + coordinate.setVersion(artifactItem.getVersion()); + coordinate.setClassifier(artifactItem.getClassifier()); final String extension; - ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler( artifactItem.getType() ); - if ( artifactHandler != null ) - { + ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler(artifactItem.getType()); + if (artifactHandler != null) { extension = artifactHandler.getExtension(); - } - else - { + } else { extension = artifactItem.getType(); } - coordinate.setExtension( extension ); + coordinate.setExtension(extension); - artifact = artifactResolver.resolveArtifact( buildingRequest, coordinate ).getArtifact(); - } - catch ( ArtifactResolverException e ) - { - throw new MojoExecutionException( "Unable to find/resolve artifact.", e ); + artifact = artifactResolver + .resolveArtifact(buildingRequest, coordinate) + .getArtifact(); + } catch (ArtifactResolverException e) { + throw new MojoExecutionException("Unable to find/resolve artifact.", e); } return artifact; @@ -267,21 +241,19 @@ protected Artifact getArtifact( ArtifactItem artifactItem ) * @param artifact representing configured file. * @throws MojoExecutionException */ - private void fillMissingArtifactVersion( ArtifactItem artifact ) - throws MojoExecutionException - { + private void fillMissingArtifactVersion(ArtifactItem artifact) throws MojoExecutionException { MavenProject project = getProject(); List deps = project.getDependencies(); - List depMngt = project.getDependencyManagement() == null ? Collections.emptyList() - : project.getDependencyManagement().getDependencies(); - - if ( !findDependencyVersion( artifact, deps, false ) - && ( project.getDependencyManagement() == null || !findDependencyVersion( artifact, depMngt, false ) ) - && !findDependencyVersion( artifact, deps, true ) - && ( project.getDependencyManagement() == null || !findDependencyVersion( artifact, depMngt, true ) ) ) - { - throw new MojoExecutionException( "Unable to find artifact version of " + artifact.getGroupId() + ":" - + artifact.getArtifactId() + " in either dependency list or in project's dependency management." ); + List depMngt = project.getDependencyManagement() == null + ? Collections.emptyList() + : project.getDependencyManagement().getDependencies(); + + if (!findDependencyVersion(artifact, deps, false) + && (project.getDependencyManagement() == null || !findDependencyVersion(artifact, depMngt, false)) + && !findDependencyVersion(artifact, deps, true) + && (project.getDependencyManagement() == null || !findDependencyVersion(artifact, depMngt, true))) { + throw new MojoExecutionException("Unable to find artifact version of " + artifact.getGroupId() + ":" + + artifact.getArtifactId() + " in either dependency list or in project's dependency management."); } } @@ -294,16 +266,13 @@ private void fillMissingArtifactVersion( ArtifactItem artifact ) * @param looseMatch only look at artifactId and groupId * @return the found dependency */ - private boolean findDependencyVersion( ArtifactItem artifact, List dependencies, boolean looseMatch ) - { - for ( Dependency dependency : dependencies ) - { - if ( Objects.equals( dependency.getArtifactId(), artifact.getArtifactId() ) - && Objects.equals( dependency.getGroupId(), artifact.getGroupId() ) - && ( looseMatch || Objects.equals( dependency.getClassifier(), artifact.getClassifier() ) ) - && ( looseMatch || Objects.equals( dependency.getType(), artifact.getType() ) ) ) - { - artifact.setVersion( dependency.getVersion() ); + private boolean findDependencyVersion(ArtifactItem artifact, List dependencies, boolean looseMatch) { + for (Dependency dependency : dependencies) { + if (Objects.equals(dependency.getArtifactId(), artifact.getArtifactId()) + && Objects.equals(dependency.getGroupId(), artifact.getGroupId()) + && (looseMatch || Objects.equals(dependency.getClassifier(), artifact.getClassifier())) + && (looseMatch || Objects.equals(dependency.getType(), artifact.getType()))) { + artifact.setVersion(dependency.getVersion()); return true; } @@ -315,88 +284,77 @@ private boolean findDependencyVersion( ArtifactItem artifact, List d /** * @return Returns the artifactItems. */ - public List getArtifactItems() - { + public List getArtifactItems() { return this.artifactItems; } /** * @param theArtifactItems The artifactItems to set. */ - public void setArtifactItems( List theArtifactItems ) - { + public void setArtifactItems(List theArtifactItems) { this.artifactItems = theArtifactItems; } /** * @return Returns the outputDirectory. */ - public File getOutputDirectory() - { + public File getOutputDirectory() { return this.outputDirectory; } /** * @param theOutputDirectory The outputDirectory to set. */ - public void setOutputDirectory( File theOutputDirectory ) - { + public void setOutputDirectory(File theOutputDirectory) { this.outputDirectory = theOutputDirectory; } /** * @return Returns the overWriteIfNewer. */ - public boolean isOverWriteIfNewer() - { + public boolean isOverWriteIfNewer() { return this.overWriteIfNewer; } /** * @param theOverWriteIfNewer The overWriteIfNewer to set. */ - public void setOverWriteIfNewer( boolean theOverWriteIfNewer ) - { + public void setOverWriteIfNewer(boolean theOverWriteIfNewer) { this.overWriteIfNewer = theOverWriteIfNewer; } /** * @return Returns the overWriteReleases. */ - public boolean isOverWriteReleases() - { + public boolean isOverWriteReleases() { return this.overWriteReleases; } /** * @param theOverWriteReleases The overWriteReleases to set. */ - public void setOverWriteReleases( boolean theOverWriteReleases ) - { + public void setOverWriteReleases(boolean theOverWriteReleases) { this.overWriteReleases = theOverWriteReleases; } /** * @return Returns the overWriteSnapshots. */ - public boolean isOverWriteSnapshots() - { + public boolean isOverWriteSnapshots() { return this.overWriteSnapshots; } /** * @param theOverWriteSnapshots The overWriteSnapshots to set. */ - public void setOverWriteSnapshots( boolean theOverWriteSnapshots ) - { + public void setOverWriteSnapshots(boolean theOverWriteSnapshots) { this.overWriteSnapshots = theOverWriteSnapshots; } /** * @param localRepositoryDirectory {@link #localRepositoryDirectory} */ - public void setLocalRepositoryDirectory( File localRepositoryDirectory ) - { + public void setLocalRepositoryDirectory(File localRepositoryDirectory) { this.localRepositoryDirectory = localRepositoryDirectory; } @@ -404,43 +362,35 @@ public void setLocalRepositoryDirectory( File localRepositoryDirectory ) * @param artifact The artifact. * @throws MojoFailureException in case of an error. */ - public void setArtifact( String artifact ) - throws MojoFailureException - { - if ( artifact != null ) - { + public void setArtifact(String artifact) throws MojoFailureException { + if (artifact != null) { String packaging = "jar"; String classifier; - String[] tokens = StringUtils.split( artifact, ":" ); - if ( tokens.length < 3 || tokens.length > 5 ) - { - throw new MojoFailureException( "Invalid artifact, " - + "you must specify groupId:artifactId:version[:packaging[:classifier]] " + artifact ); + String[] tokens = StringUtils.split(artifact, ":"); + if (tokens.length < 3 || tokens.length > 5) { + throw new MojoFailureException("Invalid artifact, " + + "you must specify groupId:artifactId:version[:packaging[:classifier]] " + artifact); } String groupId = tokens[0]; String artifactId = tokens[1]; String version = tokens[2]; - if ( tokens.length >= 4 ) - { + if (tokens.length >= 4) { packaging = tokens[3]; } - if ( tokens.length == 5 ) - { + if (tokens.length == 5) { classifier = tokens[4]; - } - else - { + } else { classifier = null; } ArtifactItem artifactItem = new ArtifactItem(); - artifactItem.setGroupId( groupId ); - artifactItem.setArtifactId( artifactId ); - artifactItem.setVersion( version ); - artifactItem.setType( packaging ); - artifactItem.setClassifier( classifier ); + artifactItem.setGroupId(groupId); + artifactItem.setArtifactId(artifactId); + artifactItem.setVersion(version); + artifactItem.setType(packaging); + artifactItem.setClassifier(classifier); - setArtifactItems( Collections.singletonList( artifactItem ) ); + setArtifactItems(Collections.singletonList(artifactItem)); } } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java index 6a8346659..214ca924a 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; import java.io.File; import java.util.Objects; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.plugins.dependency.utils.DependencyUtil; @@ -34,9 +32,7 @@ * @since 1.0 * @author Brian Fox */ -public class ArtifactItem - implements DependableCoordinate -{ +public class ArtifactItem implements DependableCoordinate { /** * Group Id of Artifact * @@ -133,28 +129,24 @@ public class ArtifactItem /** * Default ctor. */ - public ArtifactItem() - { + public ArtifactItem() { // default constructor } /** * @param artifact {@link Artifact} */ - public ArtifactItem( Artifact artifact ) - { - this.setArtifact( artifact ); - this.setArtifactId( artifact.getArtifactId() ); - this.setClassifier( artifact.getClassifier() ); - this.setGroupId( artifact.getGroupId() ); - this.setType( artifact.getType() ); - this.setVersion( artifact.getVersion() ); + public ArtifactItem(Artifact artifact) { + this.setArtifact(artifact); + this.setArtifactId(artifact.getArtifactId()); + this.setClassifier(artifact.getClassifier()); + this.setGroupId(artifact.getGroupId()); + this.setType(artifact.getType()); + this.setVersion(artifact.getVersion()); } - private String filterEmptyString( String in ) - { - if ( "".equals( in ) ) - { + private String filterEmptyString(String in) { + if ("".equals(in)) { return null; } return in; @@ -163,166 +155,142 @@ private String filterEmptyString( String in ) /** * @return Returns the artifactId. */ - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } /** * @param theArtifact The artifactId to set. */ - public void setArtifactId( String theArtifact ) - { - this.artifactId = filterEmptyString( theArtifact ); + public void setArtifactId(String theArtifact) { + this.artifactId = filterEmptyString(theArtifact); } /** * @return Returns the groupId. */ - public String getGroupId() - { + public String getGroupId() { return groupId; } /** * @param groupId The groupId to set. */ - public void setGroupId( String groupId ) - { - this.groupId = filterEmptyString( groupId ); + public void setGroupId(String groupId) { + this.groupId = filterEmptyString(groupId); } /** * @return Returns the type. */ - public String getType() - { + public String getType() { return type; } /** * @param type The type to set. */ - public void setType( String type ) - { - this.type = filterEmptyString( type ); + public void setType(String type) { + this.type = filterEmptyString(type); } /** * @return Returns the version. */ - public String getVersion() - { + public String getVersion() { return version; } /** * @param version The version to set. */ - public void setVersion( String version ) - { - this.version = filterEmptyString( version ); + public void setVersion(String version) { + this.version = filterEmptyString(version); } /** * @return Returns the base version. */ - public String getBaseVersion() - { - return ArtifactUtils.toSnapshotVersion( version ); + public String getBaseVersion() { + return ArtifactUtils.toSnapshotVersion(version); } /** * @return Classifier. */ - public String getClassifier() - { + public String getClassifier() { return classifier; } /** * @param classifier Classifier. */ - public void setClassifier( String classifier ) - { - this.classifier = filterEmptyString( classifier ); + public void setClassifier(String classifier) { + this.classifier = filterEmptyString(classifier); } @Override - public String toString() - { - if ( this.classifier == null ) - { - return groupId + ":" + artifactId + ":" + Objects.toString( version, "?" ) + ":" + type; - } - else - { - return groupId + ":" + artifactId + ":" + classifier + ":" + Objects.toString( version, "?" ) + ":" - + type; + public String toString() { + if (this.classifier == null) { + return groupId + ":" + artifactId + ":" + Objects.toString(version, "?") + ":" + type; + } else { + return groupId + ":" + artifactId + ":" + classifier + ":" + Objects.toString(version, "?") + ":" + type; } } /** * @return Returns the location. */ - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } /** * @param outputDirectory The outputDirectory to set. */ - public void setOutputDirectory( File outputDirectory ) - { + public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } /** * @return Returns the location. */ - public String getDestFileName() - { + public String getDestFileName() { return destFileName; } /** * @param destFileName The destFileName to set. */ - public void setDestFileName( String destFileName ) - { - this.destFileName = filterEmptyString( destFileName ); + public void setDestFileName(String destFileName) { + this.destFileName = filterEmptyString(destFileName); } /** * @return Returns the needsProcessing. */ - public boolean isNeedsProcessing() - { + public boolean isNeedsProcessing() { return this.needsProcessing; } /** * @param needsProcessing The needsProcessing to set. */ - public void setNeedsProcessing( boolean needsProcessing ) - { + public void setNeedsProcessing(boolean needsProcessing) { this.needsProcessing = needsProcessing; } /** * @return Returns the overWriteSnapshots. */ - public String getOverWrite() - { + public String getOverWrite() { return this.overWrite; } /** * @param overWrite The overWrite to set. */ - public void setOverWrite( String overWrite ) - { + public void setOverWrite(String overWrite) { this.overWrite = overWrite; } @@ -330,8 +298,7 @@ public void setOverWrite( String overWrite ) * @return Returns the encoding. * @since 3.0 */ - public String getEncoding() - { + public String getEncoding() { return this.encoding; } @@ -339,56 +306,49 @@ public String getEncoding() * @param encoding The encoding to set. * @since 3.0 */ - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } /** * @return Returns the artifact. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return this.artifact; } /** * @param artifact The artifact to set. */ - public void setArtifact( Artifact artifact ) - { + public void setArtifact(Artifact artifact) { this.artifact = artifact; } /** * @return Returns a comma separated list of excluded items */ - public String getExcludes() - { - return DependencyUtil.cleanToBeTokenizedString( this.excludes ); + public String getExcludes() { + return DependencyUtil.cleanToBeTokenizedString(this.excludes); } /** * @param excludes A comma separated list of items to exclude i.e. **\/*.xml, **\/*.properties */ - public void setExcludes( String excludes ) - { + public void setExcludes(String excludes) { this.excludes = excludes; } /** * @return Returns a comma separated list of included items */ - public String getIncludes() - { - return DependencyUtil.cleanToBeTokenizedString( this.includes ); + public String getIncludes() { + return DependencyUtil.cleanToBeTokenizedString(this.includes); } /** * @param includes A comma separated list of items to include i.e. **\/*.xml, **\/*.properties */ - public void setIncludes( String includes ) - { + public void setIncludes(String includes) { this.includes = includes; } @@ -398,8 +358,7 @@ public void setIncludes( String includes ) * * @since 3.1.2 */ - public FileMapper[] getFileMappers() - { + public FileMapper[] getFileMappers() { return this.fileMappers; } @@ -409,8 +368,7 @@ public FileMapper[] getFileMappers() * * @since 3.1.2 */ - public void setFileMappers( FileMapper[] fileMappers ) - { + public void setFileMappers(FileMapper[] fileMappers) { this.fileMappers = fileMappers; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java index e95d350d1..b6ccb4807 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; +import java.io.File; +import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.dependency.utils.filters.ArtifactItemFilter; -import org.apache.maven.plugins.dependency.utils.filters.DestFileFilter; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; - -import java.io.File; -import java.util.List; +import org.apache.maven.plugins.dependency.utils.filters.ArtifactItemFilter; +import org.apache.maven.plugins.dependency.utils.filters.DestFileFilter; /** * Goal that copies a list of artifacts from the repository to defined locations. @@ -36,45 +34,43 @@ * @author Brian Fox * @since 1.0 */ -@Mojo( name = "copy", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresProject = false, threadSafe = true ) -public class CopyMojo - extends AbstractFromConfigurationMojo -{ +@Mojo(name = "copy", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresProject = false, threadSafe = true) +public class CopyMojo extends AbstractFromConfigurationMojo { /** * Strip artifact version during copy */ - @Parameter( property = "mdep.stripVersion", defaultValue = "false" ) + @Parameter(property = "mdep.stripVersion", defaultValue = "false") private boolean stripVersion = false; /** * Strip artifact classifier during copy */ - @Parameter( property = "mdep.stripClassifier", defaultValue = "false" ) + @Parameter(property = "mdep.stripClassifier", defaultValue = "false") private boolean stripClassifier = false; /** * Prepend artifact groupId during copy - * + * * @since 2.7 */ - @Parameter( property = "mdep.prependGroupId", defaultValue = "false" ) + @Parameter(property = "mdep.prependGroupId", defaultValue = "false") private boolean prependGroupId = false; /** * Use artifact baseVersion during copy - * + * * @since 2.7 */ - @Parameter( property = "mdep.useBaseVersion", defaultValue = "false" ) + @Parameter(property = "mdep.useBaseVersion", defaultValue = "false") private boolean useBaseVersion = false; /** * The artifact to copy from command line. A string of the form groupId:artifactId:version[:packaging[:classifier]]. * Use {@link #artifactItems} within the POM configuration. */ - @SuppressWarnings( "unused" ) // marker-field, setArtifact(String) does the magic - @Parameter( property = "artifact" ) + @SuppressWarnings("unused") // marker-field, setArtifact(String) does the magic + @Parameter(property = "artifact") private String artifact; /** @@ -99,23 +95,16 @@ public class CopyMojo * @see #copyArtifact(ArtifactItem) */ @Override - protected void doExecute() - throws MojoExecutionException, MojoFailureException - { + protected void doExecute() throws MojoExecutionException, MojoFailureException { verifyRequirements(); - List theArtifactItems = - getProcessedArtifactItems( new ProcessArtifactItemsRequest( stripVersion, prependGroupId, useBaseVersion, - stripClassifier ) ); - for ( ArtifactItem artifactItem : theArtifactItems ) - { - if ( artifactItem.isNeedsProcessing() ) - { - copyArtifact( artifactItem ); - } - else - { - this.getLog().info( artifactItem + " already exists in " + artifactItem.getOutputDirectory() ); + List theArtifactItems = getProcessedArtifactItems( + new ProcessArtifactItemsRequest(stripVersion, prependGroupId, useBaseVersion, stripClassifier)); + for (ArtifactItem artifactItem : theArtifactItems) { + if (artifactItem.isNeedsProcessing()) { + copyArtifact(artifactItem); + } else { + this.getLog().info(artifactItem + " already exists in " + artifactItem.getOutputDirectory()); } } } @@ -127,59 +116,60 @@ protected void doExecute() * @throws MojoExecutionException with a message if an error occurs. * @see #copyFile(File, File) */ - protected void copyArtifact( ArtifactItem artifactItem ) - throws MojoExecutionException - { - File destFile = new File( artifactItem.getOutputDirectory(), artifactItem.getDestFileName() ); + protected void copyArtifact(ArtifactItem artifactItem) throws MojoExecutionException { + File destFile = new File(artifactItem.getOutputDirectory(), artifactItem.getDestFileName()); - copyFile( artifactItem.getArtifact().getFile(), destFile ); + copyFile(artifactItem.getArtifact().getFile(), destFile); } @Override - protected ArtifactItemFilter getMarkedArtifactFilter( ArtifactItem item ) - { - return new DestFileFilter( this.isOverWriteReleases(), this.isOverWriteSnapshots(), this.isOverWriteIfNewer(), - false, false, false, false, this.stripVersion, prependGroupId, useBaseVersion, - item.getOutputDirectory() ); + protected ArtifactItemFilter getMarkedArtifactFilter(ArtifactItem item) { + return new DestFileFilter( + this.isOverWriteReleases(), + this.isOverWriteSnapshots(), + this.isOverWriteIfNewer(), + false, + false, + false, + false, + this.stripVersion, + prependGroupId, + useBaseVersion, + item.getOutputDirectory()); } /** * @return Returns the stripVersion. */ - public boolean isStripVersion() - { + public boolean isStripVersion() { return this.stripVersion; } /** * @param stripVersion The stripVersion to set. */ - public void setStripVersion( boolean stripVersion ) - { + public void setStripVersion(boolean stripVersion) { this.stripVersion = stripVersion; } /** * @return Returns the stripClassifier. */ - public boolean isStripClassifier() - { + public boolean isStripClassifier() { return this.stripClassifier; } /** * @param stripClassifier The stripClassifier to set. */ - public void setStripClassifier( boolean stripClassifier ) - { + public void setStripClassifier(boolean stripClassifier) { this.stripClassifier = stripClassifier; } /** * @param useBaseVersion The useBaseVersion to set. */ - public void setUseBaseVersion( boolean useBaseVersion ) - { + public void setUseBaseVersion(boolean useBaseVersion) { this.useBaseVersion = useBaseVersion; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ProcessArtifactItemsRequest.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ProcessArtifactItemsRequest.java index 0e27b553e..e70897d5d 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ProcessArtifactItemsRequest.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ProcessArtifactItemsRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; /** * @author Olivier Lamy * @since 2.7 */ -public class ProcessArtifactItemsRequest -{ +public class ProcessArtifactItemsRequest { /** * remove the version from the filename. */ @@ -48,8 +46,7 @@ public class ProcessArtifactItemsRequest /** * Default ctor. */ - public ProcessArtifactItemsRequest() - { + public ProcessArtifactItemsRequest() { // no op } @@ -59,9 +56,8 @@ public ProcessArtifactItemsRequest() * @param useBaseVersion {@link #useBaseVersion} * @param removeClassifier {@link #removeClassifier} */ - public ProcessArtifactItemsRequest( boolean removeVersion, boolean prependGroupId, boolean useBaseVersion, - boolean removeClassifier ) - { + public ProcessArtifactItemsRequest( + boolean removeVersion, boolean prependGroupId, boolean useBaseVersion, boolean removeClassifier) { this.removeVersion = removeVersion; this.prependGroupId = prependGroupId; this.useBaseVersion = useBaseVersion; @@ -71,32 +67,28 @@ public ProcessArtifactItemsRequest( boolean removeVersion, boolean prependGroupI /** * @return {@link #removeVersion} */ - public boolean isRemoveVersion() - { + public boolean isRemoveVersion() { return removeVersion; } /** * @param removeVersion {@link #removeVersion} */ - public void setRemoveVersion( boolean removeVersion ) - { + public void setRemoveVersion(boolean removeVersion) { this.removeVersion = removeVersion; } /** * @return {@link #removeClassifier} */ - public boolean isRemoveClassifier() - { + public boolean isRemoveClassifier() { return removeClassifier; } /** * @param removeClassifier {@link #removeClassifier} */ - public void setRemoveClassifier( boolean removeClassifier ) - { + public void setRemoveClassifier(boolean removeClassifier) { this.removeClassifier = removeClassifier; } @@ -104,8 +96,7 @@ public void setRemoveClassifier( boolean removeClassifier ) * @param theRemoveVersion {@link #removeVersion} * @return {@link ProcessArtifactItemsRequest} */ - public ProcessArtifactItemsRequest removeVersion( boolean theRemoveVersion ) - { + public ProcessArtifactItemsRequest removeVersion(boolean theRemoveVersion) { this.removeVersion = theRemoveVersion; return this; } @@ -113,16 +104,14 @@ public ProcessArtifactItemsRequest removeVersion( boolean theRemoveVersion ) /** * @return {@link #prependGroupId} */ - public boolean isPrependGroupId() - { + public boolean isPrependGroupId() { return prependGroupId; } /** * @param prependGroupId {@link #prependGroupId} */ - public void setPrependGroupId( boolean prependGroupId ) - { + public void setPrependGroupId(boolean prependGroupId) { this.prependGroupId = prependGroupId; } @@ -130,8 +119,7 @@ public void setPrependGroupId( boolean prependGroupId ) * @param thePrependGroupId {@link #prependGroupId} * @return {@link ProcessArtifactItemsRequest} */ - public ProcessArtifactItemsRequest prependGroupId( boolean thePrependGroupId ) - { + public ProcessArtifactItemsRequest prependGroupId(boolean thePrependGroupId) { this.prependGroupId = thePrependGroupId; return this; } @@ -139,16 +127,14 @@ public ProcessArtifactItemsRequest prependGroupId( boolean thePrependGroupId ) /** * @return {@link #useBaseVersion} */ - public boolean isUseBaseVersion() - { + public boolean isUseBaseVersion() { return useBaseVersion; } /** * @param useBaseVersion {@link #useBaseVersion} */ - public void setUseBaseVersion( boolean useBaseVersion ) - { + public void setUseBaseVersion(boolean useBaseVersion) { this.useBaseVersion = useBaseVersion; } @@ -156,8 +142,7 @@ public void setUseBaseVersion( boolean useBaseVersion ) * @param theUseBaseVersion {@link #useBaseVersion} * @return {@link ProcessArtifactItemsRequest} */ - public ProcessArtifactItemsRequest useBaseVersion( boolean theUseBaseVersion ) - { + public ProcessArtifactItemsRequest useBaseVersion(boolean theUseBaseVersion) { this.useBaseVersion = theUseBaseVersion; return this; } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java index 8f852767f..b76add1e0 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,37 +16,35 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; +import java.io.File; +import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.dependency.utils.filters.ArtifactItemFilter; import org.apache.maven.plugins.dependency.utils.filters.MarkerFileFilter; import org.apache.maven.plugins.dependency.utils.markers.MarkerHandler; import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.codehaus.plexus.util.StringUtils; -import java.io.File; -import java.util.List; - /** * Goal that retrieves a list of artifacts from the repository and unpacks them in a defined location. * * @author Brian Fox * @since 1.0 */ -@Mojo( name = "unpack", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresProject = false, threadSafe = true ) -public class UnpackMojo - extends AbstractFromConfigurationMojo -{ +@Mojo(name = "unpack", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresProject = false, threadSafe = true) +public class UnpackMojo extends AbstractFromConfigurationMojo { /** * Directory to store flag files after unpack */ - @Parameter( defaultValue = "${project.build.directory}/dependency-maven-plugin-markers" ) + @Parameter(defaultValue = "${project.build.directory}/dependency-maven-plugin-markers") private File markersDirectory; /** @@ -58,7 +54,7 @@ public class UnpackMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "mdep.unpack.includes" ) + @Parameter(property = "mdep.unpack.includes") private String includes; /** @@ -68,7 +64,7 @@ public class UnpackMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "mdep.unpack.excludes" ) + @Parameter(property = "mdep.unpack.excludes") private String excludes; /** @@ -76,7 +72,7 @@ public class UnpackMojo * * @since 3.1.2 */ - @Parameter( property = "mdep.unpack.filemappers" ) + @Parameter(property = "mdep.unpack.filemappers") private FileMapper[] fileMappers; /** @@ -84,8 +80,8 @@ public class UnpackMojo * groupId:artifactId:version[:packaging[:classifier]]. Use {@link #artifactItems} within the POM * configuration. */ - @SuppressWarnings( "unused" ) // marker-field, setArtifact(String) does the magic - @Parameter( property = "artifact" ) + @SuppressWarnings("unused") // marker-field, setArtifact(String) does the magic + @Parameter(property = "artifact") private String artifact; /** @@ -98,26 +94,19 @@ public class UnpackMojo * @see #unpackArtifact(ArtifactItem) */ @Override - protected void doExecute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { + protected void doExecute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { return; } verifyRequirements(); - List processedItems = getProcessedArtifactItems( false ); - for ( ArtifactItem artifactItem : processedItems ) - { - if ( artifactItem.isNeedsProcessing() ) - { - unpackArtifact( artifactItem ); - } - else - { - this.getLog().info( artifactItem.getArtifact().getFile().getName() + " already unpacked." ); + List processedItems = getProcessedArtifactItems(false); + for (ArtifactItem artifactItem : processedItems) { + if (artifactItem.isNeedsProcessing()) { + unpackArtifact(artifactItem); + } else { + this.getLog().info(artifactItem.getArtifact().getFile().getName() + " already unpacked."); } } } @@ -129,24 +118,26 @@ protected void doExecute() * @throws MojoExecutionException with a message if an error occurs. * @see #getArtifact */ - private void unpackArtifact( ArtifactItem artifactItem ) - throws MojoExecutionException - { - MarkerHandler handler = new UnpackFileMarkerHandler( artifactItem, this.markersDirectory ); - - unpack( artifactItem.getArtifact(), artifactItem.getType(), artifactItem.getOutputDirectory(), - artifactItem.getIncludes(), artifactItem.getExcludes(), artifactItem.getEncoding(), - artifactItem.getFileMappers() ); + private void unpackArtifact(ArtifactItem artifactItem) throws MojoExecutionException { + MarkerHandler handler = new UnpackFileMarkerHandler(artifactItem, this.markersDirectory); + + unpack( + artifactItem.getArtifact(), + artifactItem.getType(), + artifactItem.getOutputDirectory(), + artifactItem.getIncludes(), + artifactItem.getExcludes(), + artifactItem.getEncoding(), + artifactItem.getFileMappers()); handler.setMarker(); } @Override - ArtifactItemFilter getMarkedArtifactFilter( ArtifactItem item ) - { - MarkerHandler handler = new UnpackFileMarkerHandler( item, this.markersDirectory ); + ArtifactItemFilter getMarkedArtifactFilter(ArtifactItem item) { + MarkerHandler handler = new UnpackFileMarkerHandler(item, this.markersDirectory); - return new MarkerFileFilter( this.isOverWriteReleases(), this.isOverWriteSnapshots(), this.isOverWriteIfNewer(), - handler ); + return new MarkerFileFilter( + this.isOverWriteReleases(), this.isOverWriteSnapshots(), this.isOverWriteIfNewer(), handler); } /** @@ -154,20 +145,15 @@ ArtifactItemFilter getMarkedArtifactFilter( ArtifactItem item ) * @return list of {@link ArtifactItem} * @throws MojoExecutionException in case of an error. */ - protected List getProcessedArtifactItems( boolean removeVersion ) - throws MojoExecutionException - { + protected List getProcessedArtifactItems(boolean removeVersion) throws MojoExecutionException { List items = - super.getProcessedArtifactItems( new ProcessArtifactItemsRequest( removeVersion, false, false, false ) ); - for ( ArtifactItem artifactItem : items ) - { - if ( StringUtils.isEmpty( artifactItem.getIncludes() ) ) - { - artifactItem.setIncludes( getIncludes() ); + super.getProcessedArtifactItems(new ProcessArtifactItemsRequest(removeVersion, false, false, false)); + for (ArtifactItem artifactItem : items) { + if (StringUtils.isEmpty(artifactItem.getIncludes())) { + artifactItem.setIncludes(getIncludes()); } - if ( StringUtils.isEmpty( artifactItem.getExcludes() ) ) - { - artifactItem.setExcludes( getExcludes() ); + if (StringUtils.isEmpty(artifactItem.getExcludes())) { + artifactItem.setExcludes(getExcludes()); } } return items; @@ -176,48 +162,42 @@ protected List getProcessedArtifactItems( boolean removeVersion ) /** * @return Returns the markersDirectory. */ - public File getMarkersDirectory() - { + public File getMarkersDirectory() { return this.markersDirectory; } /** * @param theMarkersDirectory The markersDirectory to set. */ - public void setMarkersDirectory( File theMarkersDirectory ) - { + public void setMarkersDirectory(File theMarkersDirectory) { this.markersDirectory = theMarkersDirectory; } /** * @return Returns a comma separated list of excluded items */ - public String getExcludes() - { + public String getExcludes() { return this.excludes; } /** * @param excludes A comma separated list of items to exclude i.e. **\/*.xml, **\/*.properties */ - public void setExcludes( String excludes ) - { + public void setExcludes(String excludes) { this.excludes = excludes; } /** * @return Returns a comma separated list of included items */ - public String getIncludes() - { + public String getIncludes() { return this.includes; } /** * @param includes A comma separated list of items to include i.e. **\/*.xml, **\/*.properties */ - public void setIncludes( String includes ) - { + public void setIncludes(String includes) { this.includes = includes; } @@ -227,8 +207,7 @@ public void setIncludes( String includes ) * * @since 3.1.2 */ - public FileMapper[] getFileMappers() - { + public FileMapper[] getFileMappers() { return this.fileMappers; } @@ -238,8 +217,7 @@ public FileMapper[] getFileMappers() * * @since 3.1.2 */ - public void setFileMappers( FileMapper[] fileMappers ) - { + public void setFileMappers(FileMapper[] fileMappers) { this.fileMappers = fileMappers; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractDependencyFilterMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractDependencyFilterMojo.java index 93e96c8cb..7d1ab01a1 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractDependencyFilterMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractDependencyFilterMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.plugin.MojoExecutionException; @@ -61,9 +59,7 @@ * @author Brian Fox * @see org.apache.maven.plugins.dependency.AbstractDependencyMojo */ -public abstract class AbstractDependencyFilterMojo - extends AbstractDependencyMojo -{ +public abstract class AbstractDependencyFilterMojo extends AbstractDependencyMojo { @Component private ArtifactResolver artifactResolver; @@ -78,7 +74,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 1.0 */ - @Parameter( property = "overWriteReleases", defaultValue = "false" ) + @Parameter(property = "overWriteReleases", defaultValue = "false") protected boolean overWriteReleases; /** @@ -86,7 +82,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 1.0 */ - @Parameter( property = "overWriteSnapshots", defaultValue = "false" ) + @Parameter(property = "overWriteSnapshots", defaultValue = "false") protected boolean overWriteSnapshots; /** @@ -94,7 +90,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "overWriteIfNewer", defaultValue = "true" ) + @Parameter(property = "overWriteIfNewer", defaultValue = "true") protected boolean overWriteIfNewer; /** @@ -102,7 +98,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "excludeTransitive", defaultValue = "false" ) + @Parameter(property = "excludeTransitive", defaultValue = "false") protected boolean excludeTransitive; /** @@ -110,7 +106,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "includeTypes", defaultValue = "" ) + @Parameter(property = "includeTypes", defaultValue = "") protected String includeTypes; /** @@ -118,7 +114,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "excludeTypes", defaultValue = "" ) + @Parameter(property = "excludeTypes", defaultValue = "") protected String excludeTypes; /** @@ -135,7 +131,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "includeScope", defaultValue = "" ) + @Parameter(property = "includeScope", defaultValue = "") protected String includeScope; /** @@ -154,7 +150,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "excludeScope", defaultValue = "" ) + @Parameter(property = "excludeScope", defaultValue = "") protected String excludeScope; /** @@ -162,7 +158,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "includeClassifiers", defaultValue = "" ) + @Parameter(property = "includeClassifiers", defaultValue = "") protected String includeClassifiers; /** @@ -170,7 +166,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "excludeClassifiers", defaultValue = "" ) + @Parameter(property = "excludeClassifiers", defaultValue = "") protected String excludeClassifiers; /** @@ -178,7 +174,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "classifier", defaultValue = "" ) + @Parameter(property = "classifier", defaultValue = "") protected String classifier; /** @@ -186,7 +182,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "type", defaultValue = "" ) + @Parameter(property = "type", defaultValue = "") protected String type; /** @@ -194,7 +190,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "excludeArtifactIds", defaultValue = "" ) + @Parameter(property = "excludeArtifactIds", defaultValue = "") protected String excludeArtifactIds; /** @@ -202,7 +198,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "includeArtifactIds", defaultValue = "" ) + @Parameter(property = "includeArtifactIds", defaultValue = "") protected String includeArtifactIds; /** @@ -210,7 +206,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "excludeGroupIds", defaultValue = "" ) + @Parameter(property = "excludeGroupIds", defaultValue = "") protected String excludeGroupIds; /** @@ -218,7 +214,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - @Parameter( property = "includeGroupIds", defaultValue = "" ) + @Parameter(property = "includeGroupIds", defaultValue = "") protected String includeGroupIds; /** @@ -226,9 +222,11 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.0 */ - //CHECKSTYLE_OFF: LineLength - @Parameter( property = "markersDirectory", defaultValue = "${project.build.directory}/dependency-maven-plugin-markers" ) - //CHECKSTYLE_ON: LineLength + // CHECKSTYLE_OFF: LineLength + @Parameter( + property = "markersDirectory", + defaultValue = "${project.build.directory}/dependency-maven-plugin-markers") + // CHECKSTYLE_ON: LineLength protected File markersDirectory; /** @@ -236,7 +234,7 @@ public abstract class AbstractDependencyFilterMojo * * @since 2.2 */ - @Parameter( property = "mdep.prependGroupId", defaultValue = "false" ) + @Parameter(property = "mdep.prependGroupId", defaultValue = "false") protected boolean prependGroupId = false; @Component @@ -259,11 +257,9 @@ public abstract class AbstractDependencyFilterMojo * @return A set of artifacts * @throws MojoExecutionException in case of errors. */ - protected Set getResolvedDependencies( boolean stopOnFailure ) - throws MojoExecutionException + protected Set getResolvedDependencies(boolean stopOnFailure) throws MojoExecutionException { - { - DependencyStatusSets status = getDependencySets( stopOnFailure ); + DependencyStatusSets status = getDependencySets(stopOnFailure); return status.getResolvedDependencies(); } @@ -273,10 +269,8 @@ protected Set getResolvedDependencies( boolean stopOnFailure ) * @return {@link DependencyStatusSets} * @throws MojoExecutionException in case of an error. */ - protected DependencyStatusSets getDependencySets( boolean stopOnFailure ) - throws MojoExecutionException - { - return getDependencySets( stopOnFailure, false ); + protected DependencyStatusSets getDependencySets(boolean stopOnFailure) throws MojoExecutionException { + return getDependencySets(stopOnFailure, false); } /** @@ -288,112 +282,97 @@ protected DependencyStatusSets getDependencySets( boolean stopOnFailure ) * @return DependencyStatusSets - Bean of TreeSets that contains information on the projects dependencies * @throws MojoExecutionException in case of errors. */ - protected DependencyStatusSets getDependencySets( boolean stopOnFailure, boolean includeParents ) - throws MojoExecutionException - { + protected DependencyStatusSets getDependencySets(boolean stopOnFailure, boolean includeParents) + throws MojoExecutionException { // add filters in well known order, least specific to most specific FilterArtifacts filter = new FilterArtifacts(); - filter.addFilter( new ProjectTransitivityFilter( getProject().getDependencyArtifacts(), - this.excludeTransitive ) ); + filter.addFilter(new ProjectTransitivityFilter(getProject().getDependencyArtifacts(), this.excludeTransitive)); - if ( "test".equals( this.excludeScope ) ) - { - throw new MojoExecutionException( "Excluding every artifact inside 'test' resolution scope means " - + "excluding everything: you probably want includeScope='compile', " - + "read parameters documentation for detailed explanations" ); + if ("test".equals(this.excludeScope)) { + throw new MojoExecutionException("Excluding every artifact inside 'test' resolution scope means " + + "excluding everything: you probably want includeScope='compile', " + + "read parameters documentation for detailed explanations"); } - filter.addFilter( new ScopeFilter( DependencyUtil.cleanToBeTokenizedString( this.includeScope ), - DependencyUtil.cleanToBeTokenizedString( this.excludeScope ) ) ); + filter.addFilter(new ScopeFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeScope), + DependencyUtil.cleanToBeTokenizedString(this.excludeScope))); - filter.addFilter( new TypeFilter( DependencyUtil.cleanToBeTokenizedString( this.includeTypes ), - DependencyUtil.cleanToBeTokenizedString( this.excludeTypes ) ) ); + filter.addFilter(new TypeFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeTypes), + DependencyUtil.cleanToBeTokenizedString(this.excludeTypes))); - filter.addFilter( new ClassifierFilter( DependencyUtil.cleanToBeTokenizedString( this.includeClassifiers ), - DependencyUtil.cleanToBeTokenizedString( this.excludeClassifiers ) ) ); + filter.addFilter(new ClassifierFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeClassifiers), + DependencyUtil.cleanToBeTokenizedString(this.excludeClassifiers))); - filter.addFilter( new GroupIdFilter( DependencyUtil.cleanToBeTokenizedString( this.includeGroupIds ), - DependencyUtil.cleanToBeTokenizedString( this.excludeGroupIds ) ) ); + filter.addFilter(new GroupIdFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeGroupIds), + DependencyUtil.cleanToBeTokenizedString(this.excludeGroupIds))); - filter.addFilter( new ArtifactIdFilter( DependencyUtil.cleanToBeTokenizedString( this.includeArtifactIds ), - DependencyUtil.cleanToBeTokenizedString( this.excludeArtifactIds ) ) ); + filter.addFilter(new ArtifactIdFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeArtifactIds), + DependencyUtil.cleanToBeTokenizedString(this.excludeArtifactIds))); // start with all artifacts. Set artifacts = getProject().getArtifacts(); - if ( includeParents ) - { + if (includeParents) { // add dependencies parents - for ( Artifact dep : new ArrayList<>( artifacts ) ) - { - addParentArtifacts( buildProjectFromArtifact( dep ), artifacts ); + for (Artifact dep : new ArrayList<>(artifacts)) { + addParentArtifacts(buildProjectFromArtifact(dep), artifacts); } // add current project parent - addParentArtifacts( getProject(), artifacts ); + addParentArtifacts(getProject(), artifacts); } // perform filtering - try - { - artifacts = filter.filter( artifacts ); - } - catch ( ArtifactFilterException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + artifacts = filter.filter(artifacts); + } catch (ArtifactFilterException e) { + throw new MojoExecutionException(e.getMessage(), e); } // transform artifacts if classifier is set DependencyStatusSets status; - if ( StringUtils.isNotEmpty( classifier ) ) - { - status = getClassifierTranslatedDependencies( artifacts, stopOnFailure ); - } - else - { - status = filterMarkedDependencies( artifacts ); + if (StringUtils.isNotEmpty(classifier)) { + status = getClassifierTranslatedDependencies(artifacts, stopOnFailure); + } else { + status = filterMarkedDependencies(artifacts); } return status; } - private MavenProject buildProjectFromArtifact( Artifact artifact ) - throws MojoExecutionException - { - try - { - return projectBuilder.build( artifact, session.getProjectBuildingRequest() ).getProject(); - } - catch ( ProjectBuildingException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + private MavenProject buildProjectFromArtifact(Artifact artifact) throws MojoExecutionException { + try { + return projectBuilder + .build(artifact, session.getProjectBuildingRequest()) + .getProject(); + } catch (ProjectBuildingException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void addParentArtifacts( MavenProject project, Set artifacts ) - throws MojoExecutionException - { - while ( project.hasParent() ) - { + private void addParentArtifacts(MavenProject project, Set artifacts) throws MojoExecutionException { + while (project.hasParent()) { project = project.getParent(); - if ( artifacts.contains( project.getArtifact() ) ) - { + if (artifacts.contains(project.getArtifact())) { // artifact already in the set break; } - try - { + try { ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); - Artifact resolvedArtifact = - artifactResolver.resolveArtifact( buildingRequest, project.getArtifact() ).getArtifact(); + Artifact resolvedArtifact = artifactResolver + .resolveArtifact(buildingRequest, project.getArtifact()) + .getArtifact(); - artifacts.add( resolvedArtifact ); - } - catch ( ArtifactResolverException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + artifacts.add(resolvedArtifact); + } catch (ArtifactResolverException e) { + throw new MojoExecutionException(e.getMessage(), e); } } } @@ -406,9 +385,8 @@ private void addParentArtifacts( MavenProject project, Set artifacts ) * @return DependencyStatusSets - Bean of TreeSets that contains information on the projects dependencies * @throws MojoExecutionException in case of an error. */ - protected DependencyStatusSets getClassifierTranslatedDependencies( Set artifacts, boolean stopOnFailure ) - throws MojoExecutionException - { + protected DependencyStatusSets getClassifierTranslatedDependencies(Set artifacts, boolean stopOnFailure) + throws MojoExecutionException { Set unResolvedArtifacts = new LinkedHashSet<>(); Set resolvedArtifacts = artifacts; DependencyStatusSets status = new DependencyStatusSets(); @@ -416,28 +394,27 @@ protected DependencyStatusSets getClassifierTranslatedDependencies( Set coordinates = translator.translate( artifacts, getLog() ); + new ClassifierTypeTranslator(artifactHandlerManager, this.classifier, this.type); + Collection coordinates = translator.translate(artifacts, getLog()); - status = filterMarkedDependencies( artifacts ); + status = filterMarkedDependencies(artifacts); // the unskipped artifacts are in the resolved set. artifacts = status.getResolvedDependencies(); // resolve the rest of the artifacts - resolvedArtifacts = resolve( new LinkedHashSet<>( coordinates ), stopOnFailure ); + resolvedArtifacts = resolve(new LinkedHashSet<>(coordinates), stopOnFailure); // calculate the artifacts not resolved. - unResolvedArtifacts.addAll( artifacts ); - unResolvedArtifacts.removeAll( resolvedArtifacts ); + unResolvedArtifacts.addAll(artifacts); + unResolvedArtifacts.removeAll(resolvedArtifacts); } // return a bean of all 3 sets. - status.setResolvedDependencies( resolvedArtifacts ); - status.setUnResolvedDependencies( unResolvedArtifacts ); + status.setResolvedDependencies(resolvedArtifacts); + status.setUnResolvedDependencies(unResolvedArtifacts); return status; } @@ -449,29 +426,24 @@ protected DependencyStatusSets getClassifierTranslatedDependencies( Set artifacts ) - throws MojoExecutionException - { + protected DependencyStatusSets filterMarkedDependencies(Set artifacts) throws MojoExecutionException { // remove files that have markers already FilterArtifacts filter = new FilterArtifacts(); filter.clearFilters(); - filter.addFilter( getMarkedArtifactFilter() ); + filter.addFilter(getMarkedArtifactFilter()); Set unMarkedArtifacts; - try - { - unMarkedArtifacts = filter.filter( artifacts ); - } - catch ( ArtifactFilterException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + unMarkedArtifacts = filter.filter(artifacts); + } catch (ArtifactFilterException e) { + throw new MojoExecutionException(e.getMessage(), e); } // calculate the skipped artifacts - Set skippedArtifacts = new LinkedHashSet<>( artifacts ); - skippedArtifacts.removeAll( unMarkedArtifacts ); + Set skippedArtifacts = new LinkedHashSet<>(artifacts); + skippedArtifacts.removeAll(unMarkedArtifacts); - return new DependencyStatusSets( unMarkedArtifacts, null, skippedArtifacts ); + return new DependencyStatusSets(unMarkedArtifacts, null, skippedArtifacts); } /** @@ -481,27 +453,23 @@ protected DependencyStatusSets filterMarkedDependencies( Set artifacts * @return the resolved artifacts. {@link Artifact}. * @throws MojoExecutionException in case of error. */ - protected Set resolve( Set coordinates, boolean stopOnFailure ) - throws MojoExecutionException - { + protected Set resolve(Set coordinates, boolean stopOnFailure) + throws MojoExecutionException { ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); Set resolvedArtifacts = new LinkedHashSet<>(); - for ( ArtifactCoordinate coordinate : coordinates ) - { - try - { - Artifact artifact = artifactResolver.resolveArtifact( buildingRequest, coordinate ).getArtifact(); - resolvedArtifacts.add( artifact ); - } - catch ( ArtifactResolverException ex ) - { + for (ArtifactCoordinate coordinate : coordinates) { + try { + Artifact artifact = artifactResolver + .resolveArtifact(buildingRequest, coordinate) + .getArtifact(); + resolvedArtifacts.add(artifact); + } catch (ArtifactResolverException ex) { // an error occurred during resolution, log it an continue - getLog().debug( "error resolving: " + coordinate ); - getLog().debug( ex ); - if ( stopOnFailure ) - { - throw new MojoExecutionException( "error resolving: " + coordinate, ex ); + getLog().debug("error resolving: " + coordinate); + getLog().debug(ex); + if (stopOnFailure) { + throw new MojoExecutionException("error resolving: " + coordinate, ex); } } } @@ -511,16 +479,14 @@ protected Set resolve( Set coordinates, boolean st /** * @return Returns the markersDirectory. */ - public File getMarkersDirectory() - { + public File getMarkersDirectory() { return this.markersDirectory; } /** * @param theMarkersDirectory The markersDirectory to set. */ - public void setMarkersDirectory( File theMarkersDirectory ) - { + public void setMarkersDirectory(File theMarkersDirectory) { this.markersDirectory = theMarkersDirectory; } @@ -529,40 +495,35 @@ public void setMarkersDirectory( File theMarkersDirectory ) /** * @return true, if the groupId should be prepended to the filename. */ - public boolean isPrependGroupId() - { + public boolean isPrependGroupId() { return prependGroupId; } /** * @param prependGroupId - true if the groupId must be prepended during the copy. */ - public void setPrependGroupId( boolean prependGroupId ) - { + public void setPrependGroupId(boolean prependGroupId) { this.prependGroupId = prependGroupId; } /** * @return {@link #artifactResolver} */ - protected final ArtifactResolver getArtifactResolver() - { + protected final ArtifactResolver getArtifactResolver() { return artifactResolver; } /** * @return {@link #dependencyResolver} */ - protected final DependencyResolver getDependencyResolver() - { + protected final DependencyResolver getDependencyResolver() { return dependencyResolver; } /** * @return {@link #repositoryManager} */ - protected final RepositoryManager getRepositoryManager() - { + protected final RepositoryManager getRepositoryManager() { return repositoryManager; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractFromDependenciesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractFromDependenciesMojo.java index aad0cb635..1226c8ada 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractFromDependenciesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/AbstractFromDependenciesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,31 +16,29 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.annotations.Parameter; +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; +import org.apache.maven.plugins.annotations.Parameter; /** * Abstract Parent class used by mojos that get Artifact information from the project dependencies. * * @author Brian Fox */ -public abstract class AbstractFromDependenciesMojo - extends AbstractDependencyFilterMojo -{ +public abstract class AbstractFromDependenciesMojo extends AbstractDependencyFilterMojo { /** * Output location. * * @since 1.0 */ - @Parameter( property = "outputDirectory", defaultValue = "${project.build.directory}/dependency" ) + @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}/dependency") protected File outputDirectory; /** * Strip artifact version during copy */ - @Parameter( property = "mdep.stripVersion", defaultValue = "false" ) + @Parameter(property = "mdep.stripVersion", defaultValue = "false") protected boolean stripVersion = false; /** @@ -50,13 +46,13 @@ public abstract class AbstractFromDependenciesMojo * * @since 3.4.0 */ - @Parameter( property = "mdep.stripType", defaultValue = "false" ) + @Parameter(property = "mdep.stripType", defaultValue = "false") protected boolean stripType = false; /** * Strip artifact classifier during copy */ - @Parameter( property = "mdep.stripClassifier", defaultValue = "false" ) + @Parameter(property = "mdep.stripClassifier", defaultValue = "false") protected boolean stripClassifier = false; /** @@ -66,14 +62,14 @@ public abstract class AbstractFromDependenciesMojo *

    * example: *

    - * + * *
          *   /outputDirectory/junit/junit/3.8.1/junit-3.8.1.jar
          * 
    * * @since 2.0-alpha-2 */ - @Parameter( property = "mdep.useRepositoryLayout", defaultValue = "false" ) + @Parameter(property = "mdep.useRepositoryLayout", defaultValue = "false") protected boolean useRepositoryLayout; /** @@ -82,7 +78,7 @@ public abstract class AbstractFromDependenciesMojo * * @since 2.2 */ - @Parameter( property = "mdep.useSubDirectoryPerScope", defaultValue = "false" ) + @Parameter(property = "mdep.useSubDirectoryPerScope", defaultValue = "false") protected boolean useSubDirectoryPerScope; /** @@ -90,7 +86,7 @@ public abstract class AbstractFromDependenciesMojo * * @since 2.0-alpha-1 */ - @Parameter( property = "mdep.useSubDirectoryPerType", defaultValue = "false" ) + @Parameter(property = "mdep.useSubDirectoryPerType", defaultValue = "false") protected boolean useSubDirectoryPerType; /** @@ -98,7 +94,7 @@ public abstract class AbstractFromDependenciesMojo * * @since 2.0-alpha-1 */ - @Parameter( property = "mdep.useSubDirectoryPerArtifact", defaultValue = "false" ) + @Parameter(property = "mdep.useSubDirectoryPerArtifact", defaultValue = "false") protected boolean useSubDirectoryPerArtifact; /** @@ -106,136 +102,118 @@ public abstract class AbstractFromDependenciesMojo * * @since 2.0-alpha-2 */ - @Parameter( property = "mdep.failOnMissingClassifierArtifact", defaultValue = "false" ) + @Parameter(property = "mdep.failOnMissingClassifierArtifact", defaultValue = "false") protected boolean failOnMissingClassifierArtifact = true; /** * @return Returns the outputDirectory. */ - public File getOutputDirectory() - { + public File getOutputDirectory() { return this.outputDirectory; } /** * @param theOutputDirectory The outputDirectory to set. */ - public void setOutputDirectory( File theOutputDirectory ) - { + public void setOutputDirectory(File theOutputDirectory) { this.outputDirectory = theOutputDirectory; } /** * @return Returns the useSubDirectoryPerArtifact. */ - public boolean isUseSubDirectoryPerArtifact() - { + public boolean isUseSubDirectoryPerArtifact() { return this.useSubDirectoryPerArtifact; } /** * @param theUseSubDirectoryPerArtifact The useSubDirectoryPerArtifact to set. */ - public void setUseSubDirectoryPerArtifact( boolean theUseSubDirectoryPerArtifact ) - { + public void setUseSubDirectoryPerArtifact(boolean theUseSubDirectoryPerArtifact) { this.useSubDirectoryPerArtifact = theUseSubDirectoryPerArtifact; } /** * @return Returns the useSubDirectoryPerScope */ - public boolean isUseSubDirectoryPerScope() - { + public boolean isUseSubDirectoryPerScope() { return this.useSubDirectoryPerScope; } /** * @param theUseSubDirectoryPerScope The useSubDirectoryPerScope to set. */ - public void setUseSubDirectoryPerScope( boolean theUseSubDirectoryPerScope ) - { + public void setUseSubDirectoryPerScope(boolean theUseSubDirectoryPerScope) { this.useSubDirectoryPerScope = theUseSubDirectoryPerScope; } /** * @return Returns the useSubDirectoryPerType. */ - public boolean isUseSubDirectoryPerType() - { + public boolean isUseSubDirectoryPerType() { return this.useSubDirectoryPerType; } /** * @param theUseSubDirectoryPerType The useSubDirectoryPerType to set. */ - public void setUseSubDirectoryPerType( boolean theUseSubDirectoryPerType ) - { + public void setUseSubDirectoryPerType(boolean theUseSubDirectoryPerType) { this.useSubDirectoryPerType = theUseSubDirectoryPerType; } /** * @return {@link #failOnMissingClassifierArtifact} */ - public boolean isFailOnMissingClassifierArtifact() - { + public boolean isFailOnMissingClassifierArtifact() { return failOnMissingClassifierArtifact; } /** * @param failOnMissingClassifierArtifact {@link #failOnMissingClassifierArtifact} */ - public void setFailOnMissingClassifierArtifact( boolean failOnMissingClassifierArtifact ) - { + public void setFailOnMissingClassifierArtifact(boolean failOnMissingClassifierArtifact) { this.failOnMissingClassifierArtifact = failOnMissingClassifierArtifact; } /** * @return {@link #stripVersion} */ - public boolean isStripVersion() - { + public boolean isStripVersion() { return stripVersion; } /** * @param stripVersion {@link #stripVersion} */ - public void setStripVersion( boolean stripVersion ) - { + public void setStripVersion(boolean stripVersion) { this.stripVersion = stripVersion; } - /** * @return {@link #stripType} */ - public boolean isStripType() - { + public boolean isStripType() { return stripType; } /** * @param stripType {@link #stripType} */ - public void setStripType( boolean stripType ) - { + public void setStripType(boolean stripType) { this.stripType = stripType; } - /** * @return true, if dependencies must be planted in a repository layout */ - public boolean isUseRepositoryLayout() - { + public boolean isUseRepositoryLayout() { return useRepositoryLayout; } /** * @param useRepositoryLayout - true if dependencies must be planted in a repository layout */ - public void setUseRepositoryLayout( boolean useRepositoryLayout ) - { + public void setUseRepositoryLayout(boolean useRepositoryLayout) { this.useRepositoryLayout = useRepositoryLayout; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/BuildClasspathMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/BuildClasspathMojo.java index 4a4176a91..8424f7084 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/BuildClasspathMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/BuildClasspathMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -36,7 +35,6 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; @@ -58,51 +56,52 @@ * @since 2.0-alpha-2 */ // CHECKSTYLE_OFF: LineLength -@Mojo( name = "build-classpath", requiresDependencyResolution = ResolutionScope.TEST, defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) +@Mojo( + name = "build-classpath", + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.GENERATE_SOURCES, + threadSafe = true) // CHECKSTYLE_ON: LineLength -public class BuildClasspathMojo - extends AbstractDependencyFilterMojo - implements Comparator -{ +public class BuildClasspathMojo extends AbstractDependencyFilterMojo implements Comparator { - @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") private String outputEncoding; - + /** * Strip artifact version during copy (only works if prefix is set) */ - @Parameter( property = "mdep.stripVersion", defaultValue = "false" ) + @Parameter(property = "mdep.stripVersion", defaultValue = "false") private boolean stripVersion = false; /** * Strip artifact classifier during copy (only works if prefix is set) */ - @Parameter( property = "mdep.stripClassifier", defaultValue = "false" ) + @Parameter(property = "mdep.stripClassifier", defaultValue = "false") private boolean stripClassifier = false; /** * The prefix to prepend on each dependent artifact. If undefined, the paths refer to the actual files store in the * local repository (the stripVersion parameter does nothing then). */ - @Parameter( property = "mdep.prefix" ) + @Parameter(property = "mdep.prefix") private String prefix; /** * A property to set to the content of the classpath string. */ - @Parameter( property = "mdep.outputProperty" ) + @Parameter(property = "mdep.outputProperty") private String outputProperty; /** * The file to write the classpath string. If undefined, it just prints the classpath as [INFO]. */ - @Parameter( property = "mdep.outputFile" ) + @Parameter(property = "mdep.outputFile") private File outputFile; /** * If 'true', it skips the up-to-date-check, and always regenerates the classpath file. */ - @Parameter( property = "mdep.regenerateFile", defaultValue = "false" ) + @Parameter(property = "mdep.regenerateFile", defaultValue = "false") private boolean regenerateFile; /** @@ -112,7 +111,7 @@ public class BuildClasspathMojo * * @since 2.0 */ - @Parameter( property = "mdep.fileSeparator", defaultValue = "" ) + @Parameter(property = "mdep.fileSeparator", defaultValue = "") private String fileSeparator; /** @@ -123,7 +122,7 @@ public class BuildClasspathMojo * * @since 2.0 */ - @Parameter( property = "mdep.pathSeparator", defaultValue = "" ) + @Parameter(property = "mdep.pathSeparator", defaultValue = "") private String pathSeparator; /** @@ -132,7 +131,7 @@ public class BuildClasspathMojo * * @since 2.0 */ - @Parameter( property = "mdep.localRepoProperty", defaultValue = "" ) + @Parameter(property = "mdep.localRepoProperty", defaultValue = "") private String localRepoProperty; /** @@ -140,7 +139,7 @@ public class BuildClasspathMojo * * @since 2.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean attach; /** @@ -148,16 +147,16 @@ public class BuildClasspathMojo * * @since 2.0 */ - @Parameter( property = "mdep.outputFilterFile", defaultValue = "false" ) + @Parameter(property = "mdep.outputFilterFile", defaultValue = "false") private boolean outputFilterFile; /** * Either append the artifact's baseVersion or uniqueVersion to the filename. Will only be used if * {@link #isStripVersion()} is {@code false}. - * + * * @since 2.6 */ - @Parameter( property = "mdep.useBaseVersion", defaultValue = "true" ) + @Parameter(property = "mdep.useBaseVersion", defaultValue = "true") private boolean useBaseVersion = true; /** @@ -176,39 +175,33 @@ public class BuildClasspathMojo * @see #getResolvedDependencies(boolean) */ @Override - protected void doExecute() - throws MojoExecutionException - { + protected void doExecute() throws MojoExecutionException { // initialize the separators. - boolean isFileSepSet = StringUtils.isNotEmpty( fileSeparator ); - boolean isPathSepSet = StringUtils.isNotEmpty( pathSeparator ); + boolean isFileSepSet = StringUtils.isNotEmpty(fileSeparator); + boolean isPathSepSet = StringUtils.isNotEmpty(pathSeparator); // don't allow them to have absolute paths when they attach. - if ( attach && StringUtils.isEmpty( localRepoProperty ) ) - { + if (attach && StringUtils.isEmpty(localRepoProperty)) { localRepoProperty = "${M2_REPO}"; } - Set artifacts = getResolvedDependencies( true ); + Set artifacts = getResolvedDependencies(true); - if ( artifacts == null || artifacts.isEmpty() ) - { - getLog().info( "No dependencies found." ); + if (artifacts == null || artifacts.isEmpty()) { + getLog().info("No dependencies found."); } - List artList = new ArrayList<>( artifacts ); + List artList = new ArrayList<>(artifacts); StringBuilder sb = new StringBuilder(); Iterator i = artList.iterator(); - if ( i.hasNext() ) - { - appendArtifactPath( i.next(), sb ); + if (i.hasNext()) { + appendArtifactPath(i.next(), sb); - while ( i.hasNext() ) - { - sb.append( isPathSepSet ? this.pathSeparator : File.pathSeparator ); - appendArtifactPath( i.next(), sb ); + while (i.hasNext()) { + sb.append(isPathSepSet ? this.pathSeparator : File.pathSeparator); + appendArtifactPath(i.next(), sb); } } @@ -216,47 +209,36 @@ protected void doExecute() // if file separator is set, I need to replace the default one from all // the file paths that were pulled from the artifacts - if ( isFileSepSet ) - { + if (isFileSepSet) { // Escape file separators to be used as literal strings - final String pattern = Pattern.quote( File.separator ); - final String replacement = Matcher.quoteReplacement( fileSeparator ); - cpString = cpString.replaceAll( pattern, replacement ); + final String pattern = Pattern.quote(File.separator); + final String replacement = Matcher.quoteReplacement(fileSeparator); + cpString = cpString.replaceAll(pattern, replacement); } // make the string valid for filtering - if ( outputFilterFile ) - { + if (outputFilterFile) { cpString = "classpath=" + cpString; } - if ( outputProperty != null ) - { - getProject().getProperties().setProperty( outputProperty, cpString ); - if ( getLog().isDebugEnabled() ) - { - getLog().debug( outputProperty + " = " + cpString ); + if (outputProperty != null) { + getProject().getProperties().setProperty(outputProperty, cpString); + if (getLog().isDebugEnabled()) { + getLog().debug(outputProperty + " = " + cpString); } } - if ( outputFile == null ) - { - getLog().info( "Dependencies classpath:" + System.lineSeparator() + cpString ); - } - else - { - if ( regenerateFile || !isUpToDate( cpString ) ) - { - storeClasspathFile( cpString, outputFile ); - } - else - { - this.getLog().info( "Skipped writing classpath file '" + outputFile + "'. No changes found." ); + if (outputFile == null) { + getLog().info("Dependencies classpath:" + System.lineSeparator() + cpString); + } else { + if (regenerateFile || !isUpToDate(cpString)) { + storeClasspathFile(cpString, outputFile); + } else { + this.getLog().info("Skipped writing classpath file '" + outputFile + "'. No changes found."); } } - if ( attach ) - { - attachFile( cpString ); + if (attach) { + attachFile(cpString); } } @@ -264,13 +246,11 @@ protected void doExecute() * @param cpString The classpath. * @throws MojoExecutionException in case of an error. */ - protected void attachFile( String cpString ) - throws MojoExecutionException - { - File attachedFile = new File( getProject().getBuild().getDirectory(), "classpath" ); - storeClasspathFile( cpString, attachedFile ); + protected void attachFile(String cpString) throws MojoExecutionException { + File attachedFile = new File(getProject().getBuild().getDirectory(), "classpath"); + storeClasspathFile(cpString, attachedFile); - projectHelper.attachArtifact( getProject(), attachedFile, "classpath" ); + projectHelper.attachArtifact(getProject(), attachedFile, "classpath"); } /** @@ -279,28 +259,23 @@ protected void attachFile( String cpString ) * @param art {@link Artifact} * @param sb {@link StringBuilder} */ - protected void appendArtifactPath( Artifact art, StringBuilder sb ) - { - if ( prefix == null ) - { + protected void appendArtifactPath(Artifact art, StringBuilder sb) { + if (prefix == null) { String file = art.getFile().getPath(); // substitute the property for the local repo path to make the classpath file portable. - if ( StringUtils.isNotEmpty( localRepoProperty ) ) - { + if (StringUtils.isNotEmpty(localRepoProperty)) { ProjectBuildingRequest projectBuildingRequest = session.getProjectBuildingRequest(); - File localBasedir = repositoryManager.getLocalRepositoryBasedir( projectBuildingRequest ); + File localBasedir = repositoryManager.getLocalRepositoryBasedir(projectBuildingRequest); - file = StringUtils.replace( file, localBasedir.getAbsolutePath(), localRepoProperty ); + file = StringUtils.replace(file, localBasedir.getAbsolutePath(), localRepoProperty); } - sb.append( file ); - } - else - { + sb.append(file); + } else { // TODO: add param for prepending groupId and version. - sb.append( prefix ); - sb.append( File.separator ); - sb.append( DependencyUtil.getFormattedFileName( art, this.stripVersion, this.prependGroupId, - this.useBaseVersion, this.stripClassifier ) ); + sb.append(prefix); + sb.append(File.separator); + sb.append(DependencyUtil.getFormattedFileName( + art, this.stripVersion, this.prependGroupId, this.useBaseVersion, this.stripClassifier)); } } @@ -310,17 +285,13 @@ protected void appendArtifactPath( Artifact art, StringBuilder sb ) * @return true if the specified classpath equals the one found inside the file, false otherwise (including when * file does not exist but new classpath does). */ - private boolean isUpToDate( String cpString ) - { - try - { + private boolean isUpToDate(String cpString) { + try { String oldCp = readClasspathFile(); - return Objects.equals( cpString, oldCp ); - } - catch ( IOException ex ) - { - this.getLog().warn( "Error while reading old classpath file '" + outputFile + "' for up-to-date check: " - + ex ); + return Objects.equals(cpString, oldCp); + } catch (IOException ex) { + this.getLog() + .warn("Error while reading old classpath file '" + outputFile + "' for up-to-date check: " + ex); return false; } @@ -331,56 +302,42 @@ private boolean isUpToDate( String cpString ) * * @param cpString the string to write into the file */ - private void storeClasspathFile( String cpString, File out ) - throws MojoExecutionException - { + private void storeClasspathFile(String cpString, File out) throws MojoExecutionException { // make sure the parent path exists. out.getParentFile().mkdirs(); - - String encoding = Objects.toString( outputEncoding, "UTF-8" ); - - try ( Writer w = - new BufferedWriter( new OutputStreamWriter( new FileOutputStream( out ), encoding ) ) ) - { - w.write( cpString ); - getLog().info( "Wrote classpath file '" + out + "'." ); - } - catch ( IOException ex ) - { - throw new MojoExecutionException( "Error while writing to classpath file '" + out, - ex ); + + String encoding = Objects.toString(outputEncoding, "UTF-8"); + + try (Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out), encoding))) { + w.write(cpString); + getLog().info("Wrote classpath file '" + out + "'."); + } catch (IOException ex) { + throw new MojoExecutionException("Error while writing to classpath file '" + out, ex); } } /** * Reads the file specified by the mojo param 'outputFile' into a string. Assumes the field * 'outputFile' is not null. - * + * * @return the string contained in the classpathFile, if it exists, or null otherwise * @throws IOException in case of an error */ - protected String readClasspathFile() - throws IOException - { - if ( outputFile == null ) - { - throw new IllegalArgumentException( "The outputFile parameter " - + "cannot be null if the file is intended to be read." ); + protected String readClasspathFile() throws IOException { + if (outputFile == null) { + throw new IllegalArgumentException( + "The outputFile parameter " + "cannot be null if the file is intended to be read."); } - if ( !outputFile.isFile() ) - { + if (!outputFile.isFile()) { return null; } StringBuilder sb = new StringBuilder(); - String encoding = Objects.toString( outputEncoding, "UTF-8" ); - - try ( BufferedReader r = - new BufferedReader( new InputStreamReader( new FileInputStream( outputFile ), encoding ) ) ) - { - for ( String line = r.readLine(); line != null; line = r.readLine() ) - { - sb.append( line ); + String encoding = Objects.toString(outputEncoding, "UTF-8"); + + try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile), encoding))) { + for (String line = r.readLine(); line != null; line = r.readLine()) { + sb.append(line); } return sb.toString(); @@ -397,102 +354,86 @@ protected String readClasspathFile() * 0 if this string is lexicographically greater than the string argument. */ @Override - public int compare( Artifact art1, Artifact art2 ) - { - if ( art1 == art2 ) - { + public int compare(Artifact art1, Artifact art2) { + if (art1 == art2) { return 0; - } - else if ( art1 == null ) - { + } else if (art1 == null) { return -1; - } - else if ( art2 == null ) - { + } else if (art2 == null) { return +1; } String s1 = art1.getGroupId() + art1.getArtifactId() + art1.getVersion(); String s2 = art2.getGroupId() + art2.getArtifactId() + art2.getVersion(); - return s1.compareTo( s2 ); + return s1.compareTo(s2); } @Override - protected ArtifactsFilter getMarkedArtifactFilter() - { + protected ArtifactsFilter getMarkedArtifactFilter() { return null; } /** * @param outputFile the outputFile to set */ - public void setOutputFile( File outputFile ) - { + public void setOutputFile(File outputFile) { this.outputFile = outputFile; } /** * @param theOutputProperty the outputProperty to set */ - public void setOutputProperty( String theOutputProperty ) - { + public void setOutputProperty(String theOutputProperty) { this.outputProperty = theOutputProperty; } /** * @param theFileSeparator the fileSeparator to set */ - public void setFileSeparator( String theFileSeparator ) - { + public void setFileSeparator(String theFileSeparator) { this.fileSeparator = theFileSeparator; } /** * @param thePathSeparator the pathSeparator to set */ - public void setPathSeparator( String thePathSeparator ) - { + public void setPathSeparator(String thePathSeparator) { this.pathSeparator = thePathSeparator; } /** * @param thePrefix the prefix to set */ - public void setPrefix( String thePrefix ) - { + public void setPrefix(String thePrefix) { this.prefix = thePrefix; } /** * @param theRegenerateFile the regenerateFile to set */ - public void setRegenerateFile( boolean theRegenerateFile ) - { + public void setRegenerateFile(boolean theRegenerateFile) { this.regenerateFile = theRegenerateFile; } /** * @return the stripVersion */ - public boolean isStripVersion() - { + public boolean isStripVersion() { return this.stripVersion; } /** * @param theStripVersion the stripVersion to set */ - public void setStripVersion( boolean theStripVersion ) - { + public void setStripVersion(boolean theStripVersion) { this.stripVersion = theStripVersion; } /** * @param localRepoProperty {@link #localRepoProperty} */ - public void setLocalRepoProperty( String localRepoProperty ) - { + public void setLocalRepoProperty(String localRepoProperty) { this.localRepoProperty = localRepoProperty; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/CopyDependenciesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/CopyDependenciesMojo.java index fd2a60362..31d2477d7 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/CopyDependenciesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/CopyDependenciesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.util.Collections; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.plugin.MojoExecutionException; @@ -48,18 +46,20 @@ * @author Brian Fox * @since 1.0 */ -//CHECKSTYLE_OFF: LineLength -@Mojo( name = "copy-dependencies", requiresDependencyResolution = ResolutionScope.TEST, defaultPhase = LifecyclePhase.PROCESS_SOURCES, threadSafe = true ) -//CHECKSTYLE_ON: LineLength -public class CopyDependenciesMojo - extends AbstractFromDependenciesMojo -{ +// CHECKSTYLE_OFF: LineLength +@Mojo( + name = "copy-dependencies", + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.PROCESS_SOURCES, + threadSafe = true) +// CHECKSTYLE_ON: LineLength +public class CopyDependenciesMojo extends AbstractFromDependenciesMojo { /** * Also copy the pom of each artifact. * * @since 2.0 */ - @Parameter( property = "mdep.copyPom", defaultValue = "false" ) + @Parameter(property = "mdep.copyPom", defaultValue = "false") protected boolean copyPom = true; /** @@ -71,24 +71,24 @@ public class CopyDependenciesMojo /** * */ - @Component( role = ArtifactRepositoryLayout.class ) + @Component(role = ArtifactRepositoryLayout.class) private Map repositoryLayouts; /** * Either append the artifact's baseVersion or uniqueVersion to the filename. Will only be used if * {@link #isStripVersion()} is {@code false}. - * + * * @since 2.6 */ - @Parameter( property = "mdep.useBaseVersion", defaultValue = "true" ) + @Parameter(property = "mdep.useBaseVersion", defaultValue = "true") protected boolean useBaseVersion = true; /** * Add parent poms to the list of copied dependencies (both current project pom parents and dependencies parents). - * + * * @since 2.8 */ - @Parameter( property = "mdep.addParentPoms", defaultValue = "false" ) + @Parameter(property = "mdep.addParentPoms", defaultValue = "false") protected boolean addParentPoms; /** @@ -111,89 +111,71 @@ public class CopyDependenciesMojo * @see #copyArtifact(Artifact, boolean, boolean, boolean, boolean) */ @Override - protected void doExecute() - throws MojoExecutionException - { - DependencyStatusSets dss = getDependencySets( this.failOnMissingClassifierArtifact, addParentPoms ); + protected void doExecute() throws MojoExecutionException { + DependencyStatusSets dss = getDependencySets(this.failOnMissingClassifierArtifact, addParentPoms); Set artifacts = dss.getResolvedDependencies(); - if ( !useRepositoryLayout ) - { - for ( Artifact artifact : artifacts ) - { - copyArtifact( artifact, isStripVersion(), this.prependGroupId, this.useBaseVersion, - this.stripClassifier ); + if (!useRepositoryLayout) { + for (Artifact artifact : artifacts) { + copyArtifact( + artifact, isStripVersion(), this.prependGroupId, this.useBaseVersion, this.stripClassifier); } - } - else - { - ProjectBuildingRequest buildingRequest = - getRepositoryManager().setLocalRepositoryBasedir( session.getProjectBuildingRequest(), - outputDirectory ); + } else { + ProjectBuildingRequest buildingRequest = getRepositoryManager() + .setLocalRepositoryBasedir(session.getProjectBuildingRequest(), outputDirectory); - artifacts.forEach( artifact -> installArtifact( artifact, buildingRequest ) ); + artifacts.forEach(artifact -> installArtifact(artifact, buildingRequest)); } Set skippedArtifacts = dss.getSkippedDependencies(); - for ( Artifact artifact : skippedArtifacts ) - { - getLog().info( artifact.getId() + " already exists in destination." ); + for (Artifact artifact : skippedArtifacts) { + getLog().info(artifact.getId() + " already exists in destination."); } - if ( isCopyPom() && !useRepositoryLayout ) - { - copyPoms( getOutputDirectory(), artifacts, this.stripVersion ); - copyPoms( getOutputDirectory(), skippedArtifacts, this.stripVersion, this.stripClassifier ); // Artifacts - // that already - // exist may - // not yet have - // poms + if (isCopyPom() && !useRepositoryLayout) { + copyPoms(getOutputDirectory(), artifacts, this.stripVersion); + copyPoms(getOutputDirectory(), skippedArtifacts, this.stripVersion, this.stripClassifier); // Artifacts + // that already + // exist may + // not yet have + // poms } } /** * install the artifact and the corresponding pom if copyPoms=true - * + * * @param artifact * @param buildingRequest */ - private void installArtifact( Artifact artifact, ProjectBuildingRequest buildingRequest ) - { - try - { - installer.install( buildingRequest, Collections.singletonList( artifact ) ); - installBaseSnapshot( artifact, buildingRequest ); - - if ( !"pom".equals( artifact.getType() ) && isCopyPom() ) - { - Artifact pomArtifact = getResolvedPomArtifact( artifact ); - if ( pomArtifact != null && pomArtifact.getFile() != null && pomArtifact.getFile().exists() ) - { - installer.install( buildingRequest, Collections.singletonList( pomArtifact ) ); - installBaseSnapshot( pomArtifact, buildingRequest ); + private void installArtifact(Artifact artifact, ProjectBuildingRequest buildingRequest) { + try { + installer.install(buildingRequest, Collections.singletonList(artifact)); + installBaseSnapshot(artifact, buildingRequest); + + if (!"pom".equals(artifact.getType()) && isCopyPom()) { + Artifact pomArtifact = getResolvedPomArtifact(artifact); + if (pomArtifact != null + && pomArtifact.getFile() != null + && pomArtifact.getFile().exists()) { + installer.install(buildingRequest, Collections.singletonList(pomArtifact)); + installBaseSnapshot(pomArtifact, buildingRequest); } } - } - catch ( ArtifactInstallerException e ) - { - getLog().warn( "unable to install " + artifact, e ); + } catch (ArtifactInstallerException e) { + getLog().warn("unable to install " + artifact, e); } } - private void installBaseSnapshot( Artifact artifact, ProjectBuildingRequest buildingRequest ) - throws ArtifactInstallerException - { - if ( artifact.isSnapshot() && !artifact.getBaseVersion().equals( artifact.getVersion() ) ) - { + private void installBaseSnapshot(Artifact artifact, ProjectBuildingRequest buildingRequest) + throws ArtifactInstallerException { + if (artifact.isSnapshot() && !artifact.getBaseVersion().equals(artifact.getVersion())) { String version = artifact.getVersion(); - try - { - artifact.setVersion( artifact.getBaseVersion() ); - installer.install( buildingRequest, Collections.singletonList( artifact ) ); - } - finally - { - artifact.setVersion( version ); + try { + artifact.setVersion(artifact.getBaseVersion()); + installer.install(buildingRequest, Collections.singletonList(artifact)); + } finally { + artifact.setVersion(version); } } } @@ -209,11 +191,10 @@ private void installBaseSnapshot( Artifact artifact, ProjectBuildingRequest buil * @throws MojoExecutionException with a message if an error occurs. * @see #copyArtifact(Artifact, boolean, boolean, boolean, boolean) */ - protected void copyArtifact( Artifact artifact, boolean removeVersion, boolean prependGroupId, - boolean theUseBaseVersion ) - throws MojoExecutionException - { - copyArtifact( artifact, removeVersion, prependGroupId, theUseBaseVersion, false ); + protected void copyArtifact( + Artifact artifact, boolean removeVersion, boolean prependGroupId, boolean theUseBaseVersion) + throws MojoExecutionException { + copyArtifact(artifact, removeVersion, prependGroupId, theUseBaseVersion, false); } /** @@ -229,63 +210,69 @@ protected void copyArtifact( Artifact artifact, boolean removeVersion, boolean p * @see #copyFile(File, File) * @see DependencyUtil#getFormattedOutputDirectory(boolean, boolean, boolean, boolean, boolean, boolean, File, Artifact) */ - protected void copyArtifact( Artifact artifact, boolean removeVersion, boolean prependGroupId, - boolean theUseBaseVersion, boolean removeClassifier ) - throws MojoExecutionException - { - - String destFileName = DependencyUtil.getFormattedFileName( artifact, removeVersion, prependGroupId, - theUseBaseVersion, removeClassifier ); - - File destDir = DependencyUtil.getFormattedOutputDirectory( useSubDirectoryPerScope, useSubDirectoryPerType, - useSubDirectoryPerArtifact, useRepositoryLayout, - stripVersion, stripType, outputDirectory, artifact ); - File destFile = new File( destDir, destFileName ); - - copyFile( artifact.getFile(), destFile ); + protected void copyArtifact( + Artifact artifact, + boolean removeVersion, + boolean prependGroupId, + boolean theUseBaseVersion, + boolean removeClassifier) + throws MojoExecutionException { + + String destFileName = DependencyUtil.getFormattedFileName( + artifact, removeVersion, prependGroupId, theUseBaseVersion, removeClassifier); + + File destDir = DependencyUtil.getFormattedOutputDirectory( + useSubDirectoryPerScope, + useSubDirectoryPerType, + useSubDirectoryPerArtifact, + useRepositoryLayout, + stripVersion, + stripType, + outputDirectory, + artifact); + File destFile = new File(destDir, destFileName); + + copyFile(artifact.getFile(), destFile); } /** * Copy the pom files associated with the artifacts. - * + * * @param destDir The destination directory {@link File}. * @param artifacts The artifacts {@link Artifact}. * @param removeVersion remove version or not. * @throws MojoExecutionException in case of errors. */ - public void copyPoms( File destDir, Set artifacts, boolean removeVersion ) - throws MojoExecutionException + public void copyPoms(File destDir, Set artifacts, boolean removeVersion) throws MojoExecutionException { - { - copyPoms( destDir, artifacts, removeVersion, false ); + copyPoms(destDir, artifacts, removeVersion, false); } /** * Copy the pom files associated with the artifacts. - * + * * @param destDir The destination directory {@link File}. * @param artifacts The artifacts {@link Artifact}. * @param removeVersion remove version or not. * @param removeClassifier remove the classifier or not. * @throws MojoExecutionException in case of errors. */ - public void copyPoms( File destDir, Set artifacts, boolean removeVersion, boolean removeClassifier ) - throws MojoExecutionException + public void copyPoms(File destDir, Set artifacts, boolean removeVersion, boolean removeClassifier) + throws MojoExecutionException { - { - for ( Artifact artifact : artifacts ) - { - Artifact pomArtifact = getResolvedPomArtifact( artifact ); + for (Artifact artifact : artifacts) { + Artifact pomArtifact = getResolvedPomArtifact(artifact); // Copy the pom - if ( pomArtifact != null && pomArtifact.getFile() != null && pomArtifact.getFile().exists() ) - { - File pomDestFile = - new File( destDir, DependencyUtil.getFormattedFileName( pomArtifact, removeVersion, prependGroupId, - useBaseVersion, removeClassifier ) ); - if ( !pomDestFile.exists() ) - { - copyFile( pomArtifact.getFile(), pomDestFile ); + if (pomArtifact != null + && pomArtifact.getFile() != null + && pomArtifact.getFile().exists()) { + File pomDestFile = new File( + destDir, + DependencyUtil.getFormattedFileName( + pomArtifact, removeVersion, prependGroupId, useBaseVersion, removeClassifier)); + if (!pomDestFile.exists()) { + copyFile(pomArtifact.getFile(), pomDestFile); } } } @@ -295,51 +282,54 @@ public void copyPoms( File destDir, Set artifacts, boolean removeVersi * @param artifact {@link Artifact} * @return {@link Artifact} */ - protected Artifact getResolvedPomArtifact( Artifact artifact ) - { + protected Artifact getResolvedPomArtifact(Artifact artifact) { DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); - coordinate.setGroupId( artifact.getGroupId() ); - coordinate.setArtifactId( artifact.getArtifactId() ); - coordinate.setVersion( artifact.getVersion() ); - coordinate.setExtension( "pom" ); + coordinate.setGroupId(artifact.getGroupId()); + coordinate.setArtifactId(artifact.getArtifactId()); + coordinate.setVersion(artifact.getVersion()); + coordinate.setExtension("pom"); Artifact pomArtifact = null; // Resolve the pom artifact using repos - try - { + try { ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); - pomArtifact = getArtifactResolver().resolveArtifact( buildingRequest, coordinate ).getArtifact(); - } - catch ( ArtifactResolverException e ) - { - getLog().info( e.getMessage() ); + pomArtifact = getArtifactResolver() + .resolveArtifact(buildingRequest, coordinate) + .getArtifact(); + } catch (ArtifactResolverException e) { + getLog().info(e.getMessage()); } return pomArtifact; } @Override - protected ArtifactsFilter getMarkedArtifactFilter() - { - return new DestFileFilter( this.overWriteReleases, this.overWriteSnapshots, this.overWriteIfNewer, - this.useSubDirectoryPerArtifact, this.useSubDirectoryPerType, - this.useSubDirectoryPerScope, this.useRepositoryLayout, this.stripVersion, - this.prependGroupId, this.useBaseVersion, this.outputDirectory ); + protected ArtifactsFilter getMarkedArtifactFilter() { + return new DestFileFilter( + this.overWriteReleases, + this.overWriteSnapshots, + this.overWriteIfNewer, + this.useSubDirectoryPerArtifact, + this.useSubDirectoryPerType, + this.useSubDirectoryPerScope, + this.useRepositoryLayout, + this.stripVersion, + this.prependGroupId, + this.useBaseVersion, + this.outputDirectory); } /** * @return true, if the pom of each artifact must be copied */ - public boolean isCopyPom() - { + public boolean isCopyPom() { return this.copyPom; } /** * @param copyPom - true if the pom of each artifact must be copied */ - public void setCopyPom( boolean copyPom ) - { + public void setCopyPom(boolean copyPom) { this.copyPom = copyPom; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java index 12a574f9f..e7c812688 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,34 +16,36 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; +import java.io.File; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; -import org.apache.maven.plugins.dependency.utils.DependencyUtil; -import org.apache.maven.plugins.dependency.utils.filters.MarkerFileFilter; -import org.apache.maven.plugins.dependency.utils.markers.DefaultFileMarkerHandler; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; +import org.apache.maven.plugins.dependency.utils.DependencyUtil; +import org.apache.maven.plugins.dependency.utils.filters.MarkerFileFilter; +import org.apache.maven.plugins.dependency.utils.markers.DefaultFileMarkerHandler; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import org.codehaus.plexus.components.io.filemappers.FileMapper; -import java.io.File; - /** * Goal that unpacks the project dependencies from the repository to a defined location. * * @author Brian Fox * @since 1.0 */ -//CHECKSTYLE_OFF: LineLength -@Mojo( name = "unpack-dependencies", requiresDependencyResolution = ResolutionScope.TEST, defaultPhase = LifecyclePhase.PROCESS_SOURCES, threadSafe = true ) -//CHECKSTYLE_ON: LineLength -public class UnpackDependenciesMojo - extends AbstractFromDependenciesMojo -{ +// CHECKSTYLE_OFF: LineLength +@Mojo( + name = "unpack-dependencies", + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.PROCESS_SOURCES, + threadSafe = true) +// CHECKSTYLE_ON: LineLength +public class UnpackDependenciesMojo extends AbstractFromDependenciesMojo { /** * A comma separated list of file patterns to include when unpacking the artifact. i.e. * **/*.xml,**/*.properties NOTE: Excludes patterns override the includes. (component code = @@ -53,7 +53,7 @@ public class UnpackDependenciesMojo * * @since 2.0 */ - @Parameter( property = "mdep.unpack.includes" ) + @Parameter(property = "mdep.unpack.includes") private String includes; /** @@ -63,15 +63,15 @@ public class UnpackDependenciesMojo * * @since 2.0 */ - @Parameter( property = "mdep.unpack.excludes" ) + @Parameter(property = "mdep.unpack.excludes") private String excludes; /** * Encoding of artifacts. - * + * * @since 3.0 */ - @Parameter( property = "mdep.unpack.encoding" ) + @Parameter(property = "mdep.unpack.encoding") private String encoding; /** @@ -79,7 +79,7 @@ public class UnpackDependenciesMojo * * @since 3.1.2 */ - @Parameter( property = "mdep.unpack.filemappers" ) + @Parameter(property = "mdep.unpack.filemappers") private FileMapper[] fileMappers; /** @@ -91,63 +91,63 @@ public class UnpackDependenciesMojo * @see #unpack(Artifact, File, String, FileMapper[]) */ @Override - protected void doExecute() - throws MojoExecutionException - { - DependencyStatusSets dss = getDependencySets( this.failOnMissingClassifierArtifact ); - - for ( Artifact artifact : dss.getResolvedDependencies() ) - { - File destDir = DependencyUtil.getFormattedOutputDirectory( useSubDirectoryPerScope, useSubDirectoryPerType, - useSubDirectoryPerArtifact, useRepositoryLayout, - stripVersion, stripType, outputDirectory, artifact ); - unpack( artifact, destDir, getIncludes(), getExcludes(), getEncoding(), getFileMappers() ); - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( artifact, this.markersDirectory ); + protected void doExecute() throws MojoExecutionException { + DependencyStatusSets dss = getDependencySets(this.failOnMissingClassifierArtifact); + + for (Artifact artifact : dss.getResolvedDependencies()) { + File destDir = DependencyUtil.getFormattedOutputDirectory( + useSubDirectoryPerScope, + useSubDirectoryPerType, + useSubDirectoryPerArtifact, + useRepositoryLayout, + stripVersion, + stripType, + outputDirectory, + artifact); + unpack(artifact, destDir, getIncludes(), getExcludes(), getEncoding(), getFileMappers()); + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(artifact, this.markersDirectory); handler.setMarker(); } - for ( Artifact artifact : dss.getSkippedDependencies() ) - { - getLog().info( artifact.getId() + " already exists in destination." ); + for (Artifact artifact : dss.getSkippedDependencies()) { + getLog().info(artifact.getId() + " already exists in destination."); } } @Override - protected ArtifactsFilter getMarkedArtifactFilter() - { - return new MarkerFileFilter( this.overWriteReleases, this.overWriteSnapshots, this.overWriteIfNewer, - new DefaultFileMarkerHandler( this.markersDirectory ) ); + protected ArtifactsFilter getMarkedArtifactFilter() { + return new MarkerFileFilter( + this.overWriteReleases, + this.overWriteSnapshots, + this.overWriteIfNewer, + new DefaultFileMarkerHandler(this.markersDirectory)); } /** * @return Returns a comma separated list of excluded items */ - public String getExcludes() - { - return DependencyUtil.cleanToBeTokenizedString( this.excludes ); + public String getExcludes() { + return DependencyUtil.cleanToBeTokenizedString(this.excludes); } /** * @param excludes A comma separated list of items to exclude i.e. **\/*.xml, **\/*.properties */ - public void setExcludes( String excludes ) - { + public void setExcludes(String excludes) { this.excludes = excludes; } /** * @return Returns a comma separated list of included items */ - public String getIncludes() - { - return DependencyUtil.cleanToBeTokenizedString( this.includes ); + public String getIncludes() { + return DependencyUtil.cleanToBeTokenizedString(this.includes); } /** * @param includes A comma separated list of items to include i.e. **\/*.xml, **\/*.properties */ - public void setIncludes( String includes ) - { + public void setIncludes(String includes) { this.includes = includes; } @@ -155,8 +155,7 @@ public void setIncludes( String includes ) * @param encoding The encoding to set. * @since 3.0 */ - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } @@ -164,8 +163,7 @@ public void setEncoding( String encoding ) * @return Returns the encoding. * @since 3.0 */ - public String getEncoding() - { + public String getEncoding() { return this.encoding; } @@ -175,8 +173,7 @@ public String getEncoding() * * @since 3.1.2 */ - public FileMapper[] getFileMappers() - { + public FileMapper[] getFileMappers() { return this.fileMappers; } @@ -186,8 +183,7 @@ public FileMapper[] getFileMappers() * * @since 3.1.2 */ - public void setFileMappers( FileMapper[] fileMappers ) - { + public void setFileMappers(FileMapper[] fileMappers) { this.fileMappers = fileMappers; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/AbstractResolveMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/AbstractResolveMojo.java index 3b65171d0..20f5a9b93 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/AbstractResolveMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/AbstractResolveMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; import java.io.File; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.dependency.fromDependencies.AbstractDependencyFilterMojo; @@ -41,16 +39,14 @@ /** * @author Brian Fox */ -public abstract class AbstractResolveMojo - extends AbstractDependencyFilterMojo -{ +public abstract class AbstractResolveMojo extends AbstractDependencyFilterMojo { /** * If specified, this parameter causes the dependencies to be written to the path specified instead of * the console. * * @since 2.0 */ - @Parameter( property = "outputFile" ) + @Parameter(property = "outputFile") protected File outputFile; /** @@ -58,7 +54,7 @@ public abstract class AbstractResolveMojo * * @since 2.2 */ - @Parameter( property = "appendOutput", defaultValue = "false" ) + @Parameter(property = "appendOutput", defaultValue = "false") protected boolean appendOutput; /** @@ -66,7 +62,7 @@ public abstract class AbstractResolveMojo * * @since 2.7 */ - @Parameter( property = "excludeReactor", defaultValue = "true" ) + @Parameter(property = "excludeReactor", defaultValue = "true") protected boolean excludeReactor; /** @@ -84,31 +80,33 @@ public abstract class AbstractResolveMojo /** * @return {@link FilterArtifacts} */ - protected FilterArtifacts getArtifactsFilter() - { + protected FilterArtifacts getArtifactsFilter() { final FilterArtifacts filter = new FilterArtifacts(); - if ( excludeReactor ) - { - - filter.addFilter( new ExcludeReactorProjectsArtifactFilter( reactorProjects, getLog() ) ); + if (excludeReactor) { + filter.addFilter(new ExcludeReactorProjectsArtifactFilter(reactorProjects, getLog())); } - filter.addFilter( new ScopeFilter( DependencyUtil.cleanToBeTokenizedString( this.includeScope ), - DependencyUtil.cleanToBeTokenizedString( this.excludeScope ) ) ); + filter.addFilter(new ScopeFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeScope), + DependencyUtil.cleanToBeTokenizedString(this.excludeScope))); - filter.addFilter( new TypeFilter( DependencyUtil.cleanToBeTokenizedString( this.includeTypes ), - DependencyUtil.cleanToBeTokenizedString( this.excludeTypes ) ) ); + filter.addFilter(new TypeFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeTypes), + DependencyUtil.cleanToBeTokenizedString(this.excludeTypes))); - filter.addFilter( new ClassifierFilter( DependencyUtil.cleanToBeTokenizedString( this.includeClassifiers ), - DependencyUtil.cleanToBeTokenizedString( this.excludeClassifiers ) ) ); + filter.addFilter(new ClassifierFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeClassifiers), + DependencyUtil.cleanToBeTokenizedString(this.excludeClassifiers))); - filter.addFilter( new GroupIdFilter( DependencyUtil.cleanToBeTokenizedString( this.includeGroupIds ), - DependencyUtil.cleanToBeTokenizedString( this.excludeGroupIds ) ) ); + filter.addFilter(new GroupIdFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeGroupIds), + DependencyUtil.cleanToBeTokenizedString(this.excludeGroupIds))); - filter.addFilter( new ArtifactIdFilter( DependencyUtil.cleanToBeTokenizedString( this.includeArtifactIds ), - DependencyUtil.cleanToBeTokenizedString( this.excludeArtifactIds ) ) ); + filter.addFilter(new ArtifactIdFilter( + DependencyUtil.cleanToBeTokenizedString(this.includeArtifactIds), + DependencyUtil.cleanToBeTokenizedString(this.excludeArtifactIds))); return filter; } @@ -120,22 +118,19 @@ protected FilterArtifacts getArtifactsFilter() * @return resolved set of dependencies * @throws DependencyResolverException in case of error while resolving artifacts. */ - protected Set resolveArtifactDependencies( final DependableCoordinate artifact ) - throws DependencyResolverException - { + protected Set resolveArtifactDependencies(final DependableCoordinate artifact) + throws DependencyResolverException { ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); Iterable artifactResults = - getDependencyResolver().resolveDependencies( buildingRequest, artifact, null ); + getDependencyResolver().resolveDependencies(buildingRequest, artifact, null); Set artifacts = new LinkedHashSet<>(); - for ( final ArtifactResult artifactResult : artifactResults ) - { - artifacts.add( artifactResult.getArtifact() ); + for (final ArtifactResult artifactResult : artifactResults) { + artifacts.add(artifactResult.getArtifact()); } return artifacts; - } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/CollectDependenciesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/CollectDependenciesMojo.java index 98152a798..bc23a637d 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/CollectDependenciesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/CollectDependenciesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; @@ -41,10 +40,11 @@ * @author Brian Fox * @since 3.0 */ -//CHECKSTYLE_OFF: LineLength -@Mojo( name = "collect", requiresDependencyCollection = ResolutionScope.TEST, defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -//CHECKSTYLE_ON: LineLength -public class CollectDependenciesMojo - extends ResolveDependenciesMojo -{ -} +// CHECKSTYLE_OFF: LineLength +@Mojo( + name = "collect", + requiresDependencyCollection = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.GENERATE_SOURCES, + threadSafe = true) +// CHECKSTYLE_ON: LineLength +public class CollectDependenciesMojo extends ResolveDependenciesMojo {} diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilter.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilter.java index 4c57ca50a..42e42fec3 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilter.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; @@ -27,49 +30,35 @@ import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.HashSet; -import java.util.Set; - /** * {@link ArtifactFilter} implementation that excludes artifacts found in the Reactor. * * @author Maarten Mulders */ -public class ExcludeReactorProjectsArtifactFilter extends AbstractArtifactsFilter -{ +public class ExcludeReactorProjectsArtifactFilter extends AbstractArtifactsFilter { private final Log log; private final Set reactorArtifactKeys; - public ExcludeReactorProjectsArtifactFilter( final List reactorProjects, final Log log ) - { + public ExcludeReactorProjectsArtifactFilter(final List reactorProjects, final Log log) { this.log = log; - this.reactorArtifactKeys = new HashSet<>( reactorProjects.size() ); - for ( final MavenProject project : reactorProjects ) - { - this.reactorArtifactKeys.add( ArtifactUtils.key( project.getArtifact() ) ); + this.reactorArtifactKeys = new HashSet<>(reactorProjects.size()); + for (final MavenProject project : reactorProjects) { + this.reactorArtifactKeys.add(ArtifactUtils.key(project.getArtifact())); } } @Override - public Set filter( final Set artifacts ) throws ArtifactFilterException - { - final Set results = new LinkedHashSet<>( artifacts.size() ); + public Set filter(final Set artifacts) throws ArtifactFilterException { + final Set results = new LinkedHashSet<>(artifacts.size()); - for ( final Artifact artifact : artifacts ) - { - if ( !isArtifactInReactor( artifact ) ) - { - results.add( artifact ); - } - else - { - if ( log.isDebugEnabled() ) - { - log.debug( "Skipped artifact " - + ArtifactUtils.key( artifact ) - + " because it is present in the reactor" ); + for (final Artifact artifact : artifacts) { + if (!isArtifactInReactor(artifact)) { + results.add(artifact); + } else { + if (log.isDebugEnabled()) { + log.debug("Skipped artifact " + + ArtifactUtils.key(artifact) + + " because it is present in the reactor"); } } } @@ -77,15 +66,12 @@ public Set filter( final Set artifacts ) throws ArtifactFilt return results; } - private boolean isArtifactInReactor( final Artifact artifact ) - { - for ( final String reactorArtifactKey : this.reactorArtifactKeys ) - { - final String artifactKey = ArtifactUtils.key( artifact ); + private boolean isArtifactInReactor(final Artifact artifact) { + for (final String reactorArtifactKey : this.reactorArtifactKeys) { + final String artifactKey = ArtifactUtils.key(artifact); // This check only includes GAV. Should we take a look at the types, too? - if ( reactorArtifactKey.equals( artifactKey ) ) - { + if (reactorArtifactKey.equals(artifactKey)) { return true; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilter.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilter.java index b429a3eac..98a60bfda 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilter.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.logging.Log; @@ -27,44 +29,33 @@ import org.apache.maven.shared.artifact.filter.resolve.Node; import org.apache.maven.shared.artifact.filter.resolve.TransformableFilter; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - /** * {@link TransformableFilter} implementation that excludes artifacts found in the Reactor. * * @author Maarten Mulders */ -public class ExcludeReactorProjectsDependencyFilter extends AbstractFilter -{ +public class ExcludeReactorProjectsDependencyFilter extends AbstractFilter { private final Log log; private final Set reactorArtifactKeys; - public ExcludeReactorProjectsDependencyFilter( final List reactorProjects, final Log log ) - { + public ExcludeReactorProjectsDependencyFilter(final List reactorProjects, final Log log) { this.log = log; this.reactorArtifactKeys = reactorProjects.stream() - .map( project -> ArtifactUtils.key( project.getArtifact() ) ) - .collect( Collectors.toSet() ); + .map(project -> ArtifactUtils.key(project.getArtifact())) + .collect(Collectors.toSet()); } @Override - public boolean accept( final Node node, final List parents ) - { + public boolean accept(final Node node, final List parents) { final Dependency dependency = node.getDependency(); - if ( dependency != null ) - { - final String dependencyArtifactKey = ArtifactUtils.key( - dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion() ); + if (dependency != null) { + final String dependencyArtifactKey = + ArtifactUtils.key(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); - final boolean result = isDependencyArtifactInReactor( dependencyArtifactKey ); + final boolean result = isDependencyArtifactInReactor(dependencyArtifactKey); - if ( log.isDebugEnabled() && result ) - { - log.debug( "Skipped dependency " - + dependencyArtifactKey - + " because it is present in the reactor" ); + if (log.isDebugEnabled() && result) { + log.debug("Skipped dependency " + dependencyArtifactKey + " because it is present in the reactor"); } return !result; @@ -72,13 +63,10 @@ public boolean accept( final Node node, final List parents ) return true; } - private boolean isDependencyArtifactInReactor( final String dependencyArtifactKey ) - { - for ( final String reactorArtifactKey : this.reactorArtifactKeys ) - { + private boolean isDependencyArtifactInReactor(final String dependencyArtifactKey) { + for (final String reactorArtifactKey : this.reactorArtifactKeys) { // This check only includes GAV. Should we take a look at the types, too? - if ( reactorArtifactKey.equals( dependencyArtifactKey ) ) - { + if (reactorArtifactKey.equals(dependencyArtifactKey)) { return true; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/GoOfflineMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/GoOfflineMojo.java index a91bd8978..a0f8e09ab 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/GoOfflineMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/GoOfflineMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.resolvers; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,22 +7,28 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import org.apache.maven.shared.artifact.filter.resolve.TransformableFilter; @@ -33,12 +37,6 @@ import org.apache.maven.shared.transfer.dependencies.DependableCoordinate; import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolverException; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.stream.Collectors; - /** * Goal that resolves all project dependencies, including plugins and reports and their dependencies. * @@ -46,10 +44,8 @@ * @author Maarten Mulders * @since 2.0 */ -@Mojo( name = "go-offline", threadSafe = true ) -public class GoOfflineMojo - extends AbstractResolveMojo -{ +@Mojo(name = "go-offline", threadSafe = true) +public class GoOfflineMojo extends AbstractResolveMojo { /** * Main entry into mojo. Gets the list of dependencies, resolves all that are not in the Reactor, and iterates * through displaying the resolved versions. @@ -57,37 +53,26 @@ public class GoOfflineMojo * @throws MojoExecutionException with a message if an error occurs. */ @Override - protected void doExecute() - throws MojoExecutionException - { + protected void doExecute() throws MojoExecutionException { - try - { + try { final Set plugins = resolvePluginArtifacts(); final Set dependencies = resolveDependencyArtifacts(); - if ( !isSilent() ) - { - for ( Artifact artifact : plugins ) - { - this.getLog().info( "Resolved plugin: " - + DependencyUtil.getFormattedFileName( artifact, false ) ); + if (!isSilent()) { + for (Artifact artifact : plugins) { + this.getLog().info("Resolved plugin: " + DependencyUtil.getFormattedFileName(artifact, false)); } - for ( Artifact artifact : dependencies ) - { - this.getLog().info( "Resolved dependency: " - + DependencyUtil.getFormattedFileName( artifact, false ) ); + for (Artifact artifact : dependencies) { + this.getLog().info("Resolved dependency: " + DependencyUtil.getFormattedFileName(artifact, false)); } } + } catch (DependencyResolverException e) { + throw new MojoExecutionException(e.getMessage(), e); } - catch ( DependencyResolverException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); - } - } /** @@ -96,57 +81,48 @@ protected void doExecute() * @return set of resolved dependency artifacts. * @throws DependencyResolverException in case of an error while resolving the artifacts. */ - protected Set resolveDependencyArtifacts() - throws DependencyResolverException - { + protected Set resolveDependencyArtifacts() throws DependencyResolverException { Collection dependencies = getProject().getDependencies(); Set dependableCoordinates = dependencies.stream() - .map( this::createDependendableCoordinateFromDependency ) - .collect( Collectors.toSet() ); + .map(this::createDependendableCoordinateFromDependency) + .collect(Collectors.toSet()); ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); - return resolveDependableCoordinate( buildingRequest, dependableCoordinates, "dependencies" ); + return resolveDependableCoordinate(buildingRequest, dependableCoordinates, "dependencies"); } - private Set resolveDependableCoordinate( final ProjectBuildingRequest buildingRequest, - final Collection dependableCoordinates, - final String type ) - throws DependencyResolverException - { + private Set resolveDependableCoordinate( + final ProjectBuildingRequest buildingRequest, + final Collection dependableCoordinates, + final String type) + throws DependencyResolverException { final TransformableFilter filter = getTransformableFilter(); - this.getLog().debug( "Resolving '" + type + "' with following repositories:" ); - for ( ArtifactRepository repo : buildingRequest.getRemoteRepositories() ) - { - getLog().debug( repo.getId() + " (" + repo.getUrl() + ")" ); + this.getLog().debug("Resolving '" + type + "' with following repositories:"); + for (ArtifactRepository repo : buildingRequest.getRemoteRepositories()) { + getLog().debug(repo.getId() + " (" + repo.getUrl() + ")"); } final Set results = new HashSet<>(); - for ( DependableCoordinate dependableCoordinate : dependableCoordinates ) - { - final Iterable artifactResults = getDependencyResolver().resolveDependencies( - buildingRequest, dependableCoordinate, filter ); + for (DependableCoordinate dependableCoordinate : dependableCoordinates) { + final Iterable artifactResults = + getDependencyResolver().resolveDependencies(buildingRequest, dependableCoordinate, filter); - for ( final ArtifactResult artifactResult : artifactResults ) - { - results.add( artifactResult.getArtifact() ); + for (final ArtifactResult artifactResult : artifactResults) { + results.add(artifactResult.getArtifact()); } } return results; } - private TransformableFilter getTransformableFilter() - { - if ( this.excludeReactor ) - { - return new ExcludeReactorProjectsDependencyFilter( this.reactorProjects, getLog() ); - } - else - { + private TransformableFilter getTransformableFilter() { + if (this.excludeReactor) { + return new ExcludeReactorProjectsDependencyFilter(this.reactorProjects, getLog()); + } else { return null; } } @@ -157,54 +133,48 @@ private TransformableFilter getTransformableFilter() * @return set of resolved plugin artifacts. * @throws DependencyResolverException in case of an error while resolving the artifacts. */ - protected Set resolvePluginArtifacts() - throws DependencyResolverException - { + protected Set resolvePluginArtifacts() throws DependencyResolverException { Set plugins = getProject().getPluginArtifacts(); Set reports = getProject().getReportArtifacts(); Set artifacts = new LinkedHashSet<>(); - artifacts.addAll( reports ); - artifacts.addAll( plugins ); + artifacts.addAll(reports); + artifacts.addAll(plugins); Set dependableCoordinates = artifacts.stream() - .map( this::createDependendableCoordinateFromArtifact ) - .collect( Collectors.toSet() ); - + .map(this::createDependendableCoordinateFromArtifact) + .collect(Collectors.toSet()); ProjectBuildingRequest buildingRequest = newResolvePluginProjectBuildingRequest(); - return resolveDependableCoordinate( buildingRequest, dependableCoordinates, "plugins" ); + return resolveDependableCoordinate(buildingRequest, dependableCoordinates, "plugins"); } - private DependableCoordinate createDependendableCoordinateFromArtifact( final Artifact artifact ) - { + private DependableCoordinate createDependendableCoordinateFromArtifact(final Artifact artifact) { final DefaultDependableCoordinate result = new DefaultDependableCoordinate(); - result.setGroupId( artifact.getGroupId() ); - result.setArtifactId( artifact.getArtifactId() ); - result.setVersion( artifact.getVersion() ); - result.setType( artifact.getType() ); - result.setClassifier( artifact.getClassifier() ); + result.setGroupId(artifact.getGroupId()); + result.setArtifactId(artifact.getArtifactId()); + result.setVersion(artifact.getVersion()); + result.setType(artifact.getType()); + result.setClassifier(artifact.getClassifier()); return result; } - private DependableCoordinate createDependendableCoordinateFromDependency( final Dependency dependency ) - { + private DependableCoordinate createDependendableCoordinateFromDependency(final Dependency dependency) { final DefaultDependableCoordinate result = new DefaultDependableCoordinate(); - result.setGroupId( dependency.getGroupId() ); - result.setArtifactId( dependency.getArtifactId() ); - result.setVersion( dependency.getVersion() ); - result.setType( dependency.getType() ); - result.setClassifier( dependency.getClassifier() ); + result.setGroupId(dependency.getGroupId()); + result.setArtifactId(dependency.getArtifactId()); + result.setVersion(dependency.getVersion()); + result.setType(dependency.getType()); + result.setClassifier(dependency.getClassifier()); return result; } @Override - protected ArtifactsFilter getMarkedArtifactFilter() - { + protected ArtifactsFilter getMarkedArtifactFilter() { return null; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListMojo.java index c4bc2abda..54cb52c46 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,15 +7,16 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -28,9 +27,7 @@ * @author Mark Hobson * @since 2.0-alpha-5 */ -@Mojo( name = "list", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -public class ListMojo - extends ResolveDependenciesMojo -{ +@Mojo(name = "list", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +public class ListMojo extends ResolveDependenciesMojo { // alias for dependency:resolve } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListRepositoriesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListRepositoriesMojo.java index deed8d34d..59a785ce3 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListRepositoriesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ListRepositoriesMojo.java @@ -1,76 +1,66 @@ -package org.apache.maven.plugins.dependency.resolvers; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.plugins.dependency.AbstractDependencyMojo; -import org.apache.maven.shared.transfer.dependencies.collect.CollectorResult; -import org.apache.maven.shared.transfer.dependencies.collect.DependencyCollector; -import org.apache.maven.shared.transfer.dependencies.collect.DependencyCollectorException; - -/** - * Goal that resolves all project dependencies and then lists the repositories used by the build and by the transitive - * dependencies - * - * @author Brian Fox - * @since 2.2 - */ -@Mojo( name = "list-repositories", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -public class ListRepositoriesMojo - extends AbstractDependencyMojo -{ - /** - * Dependency collector, needed to resolve dependencies. - */ - @Component( role = DependencyCollector.class ) - private DependencyCollector dependencyCollector; - - /** - * Displays a list of the repositories used by this build. - * - * @throws MojoExecutionException with a message if an error occurs. - */ - @Override - protected void doExecute() - throws MojoExecutionException - { - try - { - CollectorResult collectResult = - dependencyCollector.collectDependencies( session.getProjectBuildingRequest(), getProject().getModel() ); - - this.getLog().info( "Repositories used by this build:" ); - - for ( ArtifactRepository repo : collectResult.getRemoteRepositories() ) - { - this.getLog().info( repo.toString() ); - } - } - catch ( DependencyCollectorException e ) - { - throw new MojoExecutionException( "Unable to resolve artifacts", e ); - } - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.dependency.resolvers; + +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.plugins.dependency.AbstractDependencyMojo; +import org.apache.maven.shared.transfer.dependencies.collect.CollectorResult; +import org.apache.maven.shared.transfer.dependencies.collect.DependencyCollector; +import org.apache.maven.shared.transfer.dependencies.collect.DependencyCollectorException; + +/** + * Goal that resolves all project dependencies and then lists the repositories used by the build and by the transitive + * dependencies + * + * @author Brian Fox + * @since 2.2 + */ +@Mojo(name = "list-repositories", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +public class ListRepositoriesMojo extends AbstractDependencyMojo { + /** + * Dependency collector, needed to resolve dependencies. + */ + @Component(role = DependencyCollector.class) + private DependencyCollector dependencyCollector; + + /** + * Displays a list of the repositories used by this build. + * + * @throws MojoExecutionException with a message if an error occurs. + */ + @Override + protected void doExecute() throws MojoExecutionException { + try { + CollectorResult collectResult = dependencyCollector.collectDependencies( + session.getProjectBuildingRequest(), getProject().getModel()); + + this.getLog().info("Repositories used by this build:"); + + for (ArtifactRepository repo : collectResult.getRemoteRepositories()) { + this.getLog().info(repo.toString()); + } + } catch (DependencyCollectorException e) { + throw new MojoExecutionException("Unable to resolve artifacts", e); + } + } +} diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java index c44535276..be09c9afb 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,21 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; -import org.apache.maven.plugins.dependency.utils.DependencyUtil; -import org.apache.maven.plugins.dependency.utils.filters.ResolveFileFilter; -import org.apache.maven.plugins.dependency.utils.markers.SourcesFileMarkerHandler; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; -import org.apache.maven.shared.utils.logging.MessageBuilder; -import org.apache.maven.shared.utils.logging.MessageUtils; +package org.apache.maven.plugins.dependency.resolvers; import java.io.File; import java.io.IOException; @@ -46,6 +30,19 @@ import java.util.Set; import java.util.jar.JarFile; import java.util.jar.Manifest; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; +import org.apache.maven.plugins.dependency.utils.DependencyUtil; +import org.apache.maven.plugins.dependency.utils.filters.ResolveFileFilter; +import org.apache.maven.plugins.dependency.utils.markers.SourcesFileMarkerHandler; +import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; +import org.apache.maven.shared.utils.logging.MessageBuilder; +import org.apache.maven.shared.utils.logging.MessageUtils; /** * Goal that resolves the project dependencies from the repository. When using this goal while running on Java 9 the @@ -54,14 +51,16 @@ * @author Brian Fox * @since 2.0 */ -//CHECKSTYLE_OFF: LineLength -@Mojo( name = "resolve", requiresDependencyResolution = ResolutionScope.TEST, defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -//CHECKSTYLE_ON: LineLength -public class ResolveDependenciesMojo - extends AbstractResolveMojo -{ - - @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) +// CHECKSTYLE_OFF: LineLength +@Mojo( + name = "resolve", + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.GENERATE_SOURCES, + threadSafe = true) +// CHECKSTYLE_ON: LineLength +public class ResolveDependenciesMojo extends AbstractResolveMojo { + + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") private String outputEncoding; /** @@ -69,7 +68,7 @@ public class ResolveDependenciesMojo * * @since 2.0-alpha-2 */ - @Parameter( property = "mdep.outputScope", defaultValue = "true" ) + @Parameter(property = "mdep.outputScope", defaultValue = "true") protected boolean outputScope; /** @@ -79,18 +78,18 @@ public class ResolveDependenciesMojo /** * Sort the output list of resolved artifacts alphabetically. The default ordering matches the classpath order. - * + * * @since 2.8 */ - @Parameter( property = "sort", defaultValue = "false" ) + @Parameter(property = "sort", defaultValue = "false") boolean sort; /** * Include parent poms in the dependency resolution list. - * + * * @since 2.8 */ - @Parameter( property = "includeParents", defaultValue = "false" ) + @Parameter(property = "includeParents", defaultValue = "false") boolean includeParents; /** @@ -99,43 +98,33 @@ public class ResolveDependenciesMojo * @throws MojoExecutionException with a message if an error occurs */ @Override - protected void doExecute() - throws MojoExecutionException - { + protected void doExecute() throws MojoExecutionException { // get sets of dependencies - results = this.getDependencySets( false, includeParents ); - - String output = getOutput( outputAbsoluteArtifactFilename, outputScope, sort ); - try - { - if ( outputFile == null ) - { - DependencyUtil.log( output, getLog() ); + results = this.getDependencySets(false, includeParents); + + String output = getOutput(outputAbsoluteArtifactFilename, outputScope, sort); + try { + if (outputFile == null) { + DependencyUtil.log(output, getLog()); + } else { + String encoding = Objects.toString(outputEncoding, "UTF-8"); + DependencyUtil.write(output, outputFile, appendOutput, encoding); } - else - { - String encoding = Objects.toString( outputEncoding, "UTF-8" ); - DependencyUtil.write( output, outputFile, appendOutput, encoding ); - } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } /** * @return returns the results */ - public DependencyStatusSets getResults() - { + public DependencyStatusSets getResults() { return this.results; } @Override - protected ArtifactsFilter getMarkedArtifactFilter() - { - return new ResolveFileFilter( new SourcesFileMarkerHandler( this.markersDirectory ) ); + protected ArtifactsFilter getMarkedArtifactFilter() { + return new ResolveFileFilter(new SourcesFileMarkerHandler(this.markersDirectory)); } /** @@ -144,201 +133,162 @@ protected ArtifactsFilter getMarkedArtifactFilter() * @param theSort sort yes/no * @return the output */ - public String getOutput( boolean outputAbsoluteArtifactFilename, boolean theOutputScope, boolean theSort ) - { + public String getOutput(boolean outputAbsoluteArtifactFilename, boolean theOutputScope, boolean theSort) { StringBuilder sb = new StringBuilder(); - sb.append( System.lineSeparator() ); - sb.append( "The following files have been resolved:" ); - sb.append( System.lineSeparator() ); - if ( results.getResolvedDependencies() == null || results.getResolvedDependencies().isEmpty() ) - { - sb.append( " none" ); - sb.append( System.lineSeparator() ); - } - else - { - sb.append( buildArtifactListOutput( results.getResolvedDependencies(), outputAbsoluteArtifactFilename, - theOutputScope, theSort ) ); + sb.append(System.lineSeparator()); + sb.append("The following files have been resolved:"); + sb.append(System.lineSeparator()); + if (results.getResolvedDependencies() == null + || results.getResolvedDependencies().isEmpty()) { + sb.append(" none"); + sb.append(System.lineSeparator()); + } else { + sb.append(buildArtifactListOutput( + results.getResolvedDependencies(), outputAbsoluteArtifactFilename, theOutputScope, theSort)); } - if ( results.getSkippedDependencies() != null && !results.getSkippedDependencies().isEmpty() ) - { - sb.append( System.lineSeparator() ); - sb.append( "The following files were skipped:" ); - sb.append( System.lineSeparator() ); - Set skippedDependencies = new LinkedHashSet<>( results.getSkippedDependencies() ); - sb.append( buildArtifactListOutput( skippedDependencies, outputAbsoluteArtifactFilename, theOutputScope, - theSort ) ); + if (results.getSkippedDependencies() != null + && !results.getSkippedDependencies().isEmpty()) { + sb.append(System.lineSeparator()); + sb.append("The following files were skipped:"); + sb.append(System.lineSeparator()); + Set skippedDependencies = new LinkedHashSet<>(results.getSkippedDependencies()); + sb.append(buildArtifactListOutput( + skippedDependencies, outputAbsoluteArtifactFilename, theOutputScope, theSort)); } - if ( results.getUnResolvedDependencies() != null && !results.getUnResolvedDependencies().isEmpty() ) - { - sb.append( System.lineSeparator() ); - sb.append( "The following files have NOT been resolved:" ); - sb.append( System.lineSeparator() ); - Set unResolvedDependencies = new LinkedHashSet<>( results.getUnResolvedDependencies() ); - sb.append( buildArtifactListOutput( unResolvedDependencies, outputAbsoluteArtifactFilename, theOutputScope, - theSort ) ); + if (results.getUnResolvedDependencies() != null + && !results.getUnResolvedDependencies().isEmpty()) { + sb.append(System.lineSeparator()); + sb.append("The following files have NOT been resolved:"); + sb.append(System.lineSeparator()); + Set unResolvedDependencies = new LinkedHashSet<>(results.getUnResolvedDependencies()); + sb.append(buildArtifactListOutput( + unResolvedDependencies, outputAbsoluteArtifactFilename, theOutputScope, theSort)); } - sb.append( System.lineSeparator() ); + sb.append(System.lineSeparator()); return sb.toString(); } - private StringBuilder buildArtifactListOutput( Set artifacts, boolean outputAbsoluteArtifactFilename, - boolean theOutputScope, boolean theSort ) - { + private StringBuilder buildArtifactListOutput( + Set artifacts, boolean outputAbsoluteArtifactFilename, boolean theOutputScope, boolean theSort) { StringBuilder sb = new StringBuilder(); List artifactStringList = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { MessageBuilder messageBuilder = MessageUtils.buffer(); - messageBuilder.a( " " ); + messageBuilder.a(" "); - if ( theOutputScope ) - { - messageBuilder.a( artifact.toString() ); - } - else - { - messageBuilder.a( artifact.getId() ); + if (theOutputScope) { + messageBuilder.a(artifact.toString()); + } else { + messageBuilder.a(artifact.getId()); } - if ( outputAbsoluteArtifactFilename ) - { - try - { + if (outputAbsoluteArtifactFilename) { + try { // we want to print the absolute file name here - String artifactFilename = artifact.getFile().getAbsoluteFile().getPath(); + String artifactFilename = + artifact.getFile().getAbsoluteFile().getPath(); - messageBuilder.a( ':' ).a( artifactFilename ); - } - catch ( NullPointerException e ) - { + messageBuilder.a(':').a(artifactFilename); + } catch (NullPointerException e) { // ignore the null pointer, we'll output a null string } } - if ( theOutputScope && artifact.isOptional() ) - { - messageBuilder.a( " (optional)" ); + if (theOutputScope && artifact.isOptional()) { + messageBuilder.a(" (optional)"); } // dependencies:collect won't download jars - if ( artifact.getFile() != null ) - { - ModuleDescriptor moduleDescriptor = getModuleDescriptor( artifact.getFile() ); - if ( moduleDescriptor != null ) - { - messageBuilder.project( " -- module " + moduleDescriptor.name ); - - if ( moduleDescriptor.automatic ) - { - if ( "MANIFEST".equals( moduleDescriptor.moduleNameSource ) ) - { - messageBuilder.strong( " [auto]" ); - } - else - { - messageBuilder.warning( " (auto)" ); + if (artifact.getFile() != null) { + ModuleDescriptor moduleDescriptor = getModuleDescriptor(artifact.getFile()); + if (moduleDescriptor != null) { + messageBuilder.project(" -- module " + moduleDescriptor.name); + + if (moduleDescriptor.automatic) { + if ("MANIFEST".equals(moduleDescriptor.moduleNameSource)) { + messageBuilder.strong(" [auto]"); + } else { + messageBuilder.warning(" (auto)"); } } } } - artifactStringList.add( messageBuilder + System.lineSeparator() ); + artifactStringList.add(messageBuilder + System.lineSeparator()); } - if ( theSort ) - { - Collections.sort( artifactStringList ); + if (theSort) { + Collections.sort(artifactStringList); } - for ( String artifactString : artifactStringList ) - { - sb.append( artifactString ); + for (String artifactString : artifactStringList) { + sb.append(artifactString); } return sb; } - private ModuleDescriptor getModuleDescriptor( File artifactFile ) - { + private ModuleDescriptor getModuleDescriptor(File artifactFile) { ModuleDescriptor moduleDescriptor = null; - try - { + try { // Use Java9 code to get moduleName, don't try to do it better with own implementation - Class moduleFinderClass = Class.forName( "java.lang.module.ModuleFinder" ); + Class moduleFinderClass = Class.forName("java.lang.module.ModuleFinder"); java.nio.file.Path path = artifactFile.toPath(); - Method ofMethod = moduleFinderClass.getMethod( "of", java.nio.file.Path[].class ); - Object moduleFinderInstance = ofMethod.invoke( null, new Object[] { new java.nio.file.Path[] { path } } ); + Method ofMethod = moduleFinderClass.getMethod("of", java.nio.file.Path[].class); + Object moduleFinderInstance = ofMethod.invoke(null, new Object[] {new java.nio.file.Path[] {path}}); - Method findAllMethod = moduleFinderClass.getMethod( "findAll" ); - Set moduleReferences = (Set) findAllMethod.invoke( moduleFinderInstance ); + Method findAllMethod = moduleFinderClass.getMethod("findAll"); + Set moduleReferences = (Set) findAllMethod.invoke(moduleFinderInstance); // moduleReferences can be empty when referring to target/classes without module-info.class - if ( !moduleReferences.isEmpty() ) - { + if (!moduleReferences.isEmpty()) { Object moduleReference = moduleReferences.iterator().next(); - Method descriptorMethod = moduleReference.getClass().getMethod( "descriptor" ); - Object moduleDescriptorInstance = descriptorMethod.invoke( moduleReference ); + Method descriptorMethod = moduleReference.getClass().getMethod("descriptor"); + Object moduleDescriptorInstance = descriptorMethod.invoke(moduleReference); - Method nameMethod = moduleDescriptorInstance.getClass().getMethod( "name" ); - String name = (String) nameMethod.invoke( moduleDescriptorInstance ); + Method nameMethod = moduleDescriptorInstance.getClass().getMethod("name"); + String name = (String) nameMethod.invoke(moduleDescriptorInstance); moduleDescriptor = new ModuleDescriptor(); moduleDescriptor.name = name; - Method isAutomaticMethod = moduleDescriptorInstance.getClass().getMethod( "isAutomatic" ); - moduleDescriptor.automatic = (Boolean) isAutomaticMethod.invoke( moduleDescriptorInstance ); + Method isAutomaticMethod = moduleDescriptorInstance.getClass().getMethod("isAutomatic"); + moduleDescriptor.automatic = (Boolean) isAutomaticMethod.invoke(moduleDescriptorInstance); - if ( moduleDescriptor.automatic ) - { - if ( artifactFile.isFile() ) - { - try ( JarFile jarFile = new JarFile( artifactFile ) ) - { + if (moduleDescriptor.automatic) { + if (artifactFile.isFile()) { + try (JarFile jarFile = new JarFile(artifactFile)) { Manifest manifest = jarFile.getManifest(); - if ( manifest != null - && manifest.getMainAttributes().getValue( "Automatic-Module-Name" ) != null ) - { + if (manifest != null + && manifest.getMainAttributes().getValue("Automatic-Module-Name") != null) { moduleDescriptor.moduleNameSource = "MANIFEST"; - } - else - { + } else { moduleDescriptor.moduleNameSource = "FILENAME"; } - } - catch ( IOException e ) - { + } catch (IOException e) { // noop } } } } - } - catch ( ClassNotFoundException | SecurityException | IllegalAccessException | IllegalArgumentException e ) - { + } catch (ClassNotFoundException | SecurityException | IllegalAccessException | IllegalArgumentException e) { // do nothing - } - catch ( NoSuchMethodException e ) - { + } catch (NoSuchMethodException e) { e.printStackTrace(); - } - catch ( InvocationTargetException e ) - { + } catch (InvocationTargetException e) { Throwable cause = e.getCause(); - while ( cause.getCause() != null ) - { + while (cause.getCause() != null) { cause = cause.getCause(); } - getLog().info( "Can't extract module name from " + artifactFile.getName() + ": " + cause.getMessage() ); + getLog().info("Can't extract module name from " + artifactFile.getName() + ": " + cause.getMessage()); } return moduleDescriptor; } - private class ModuleDescriptor - { + private class ModuleDescriptor { String name; boolean automatic = true; diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependencySourcesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependencySourcesMojo.java index 95d168805..63acc3e3a 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependencySourcesMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependencySourcesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugin.MojoExecutionException; @@ -31,12 +30,14 @@ * @author Brian Fox * @since 2.0-alpha2 */ -//CHECKSTYLE_OFF: LineLength -@Mojo( name = "sources", defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -//CHECKSTYLE_ON: LineLength -public class ResolveDependencySourcesMojo - extends ResolveDependenciesMojo -{ +// CHECKSTYLE_OFF: LineLength +@Mojo( + name = "sources", + defaultPhase = LifecyclePhase.GENERATE_SOURCES, + requiresDependencyResolution = ResolutionScope.TEST, + threadSafe = true) +// CHECKSTYLE_ON: LineLength +public class ResolveDependencySourcesMojo extends ResolveDependenciesMojo { private static final String SOURCE_CLASSIFIER = "sources"; @@ -46,11 +47,8 @@ public class ResolveDependencySourcesMojo * @throws MojoExecutionException with a message if an error occurs. */ @Override - protected void doExecute() - throws MojoExecutionException - { - if ( StringUtils.isEmpty( this.classifier ) ) - { + protected void doExecute() throws MojoExecutionException { + if (StringUtils.isEmpty(this.classifier)) { this.classifier = SOURCE_CLASSIFIER; } diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvePluginsMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvePluginsMojo.java index c40c4276e..b2393f717 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvePluginsMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvePluginsMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; import java.io.IOException; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -44,12 +42,10 @@ * @author Brian Fox * @since 2.0 */ -@Mojo( name = "resolve-plugins", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ResolvePluginsMojo - extends AbstractResolveMojo -{ +@Mojo(name = "resolve-plugins", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ResolvePluginsMojo extends AbstractResolveMojo { - @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") private String outputEncoding; /** @@ -58,97 +54,77 @@ public class ResolvePluginsMojo * @throws MojoExecutionException with a message if an error occurs. */ @Override - protected void doExecute() - throws MojoExecutionException - { - try - { + protected void doExecute() throws MojoExecutionException { + try { // ideally this should either be DependencyCoordinates or DependencyNode final Set plugins = resolvePluginArtifacts(); StringBuilder sb = new StringBuilder(); - sb.append( System.lineSeparator() ); - sb.append( "The following plugins have been resolved:" ); - sb.append( System.lineSeparator() ); - if ( plugins == null || plugins.isEmpty() ) - { - sb.append( " none" ); - sb.append( System.lineSeparator() ); - } - else - { - for ( Artifact plugin : plugins ) - { + sb.append(System.lineSeparator()); + sb.append("The following plugins have been resolved:"); + sb.append(System.lineSeparator()); + if (plugins == null || plugins.isEmpty()) { + sb.append(" none"); + sb.append(System.lineSeparator()); + } else { + for (Artifact plugin : plugins) { String artifactFilename = null; - if ( outputAbsoluteArtifactFilename ) - { - try - { + if (outputAbsoluteArtifactFilename) { + try { // we want to print the absolute file name here - artifactFilename = plugin.getFile().getAbsoluteFile().getPath(); - } - catch ( NullPointerException e ) - { + artifactFilename = + plugin.getFile().getAbsoluteFile().getPath(); + } catch (NullPointerException e) { // ignore the null pointer, we'll output a null string artifactFilename = null; } } String id = plugin.toString(); - sb.append( " " ) - .append( id ) - .append( outputAbsoluteArtifactFilename ? ":" + artifactFilename : "" ) - .append( System.lineSeparator() ); + sb.append(" ") + .append(id) + .append(outputAbsoluteArtifactFilename ? ":" + artifactFilename : "") + .append(System.lineSeparator()); - if ( !excludeTransitive ) - { + if (!excludeTransitive) { DefaultDependableCoordinate pluginCoordinate = new DefaultDependableCoordinate(); - pluginCoordinate.setGroupId( plugin.getGroupId() ); - pluginCoordinate.setArtifactId( plugin.getArtifactId() ); - pluginCoordinate.setVersion( plugin.getVersion() ); + pluginCoordinate.setGroupId(plugin.getGroupId()); + pluginCoordinate.setArtifactId(plugin.getArtifactId()); + pluginCoordinate.setVersion(plugin.getVersion()); - for ( final Artifact artifact : resolveArtifactDependencies( pluginCoordinate ) ) - { + for (final Artifact artifact : resolveArtifactDependencies(pluginCoordinate)) { artifactFilename = null; - if ( outputAbsoluteArtifactFilename ) - { - try - { + if (outputAbsoluteArtifactFilename) { + try { // we want to print the absolute file name here - artifactFilename = artifact.getFile().getAbsoluteFile().getPath(); - } - catch ( NullPointerException e ) - { + artifactFilename = + artifact.getFile().getAbsoluteFile().getPath(); + } catch (NullPointerException e) { // ignore the null pointer, we'll output a null string artifactFilename = null; } } id = artifact.toString(); - sb.append( " " ) - .append( id ) - .append( outputAbsoluteArtifactFilename ? ":" + artifactFilename : "" ) - .append( System.lineSeparator() ); + sb.append(" ") + .append(id) + .append(outputAbsoluteArtifactFilename ? ":" + artifactFilename : "") + .append(System.lineSeparator()); } } } - sb.append( System.lineSeparator() ); + sb.append(System.lineSeparator()); String output = sb.toString(); - if ( outputFile == null ) - { - DependencyUtil.log( output, getLog() ); - } - else - { - String encoding = Objects.toString( outputEncoding, "UTF-8" ); - DependencyUtil.write( output, outputFile, appendOutput, encoding ); + if (outputFile == null) { + DependencyUtil.log(output, getLog()); + } else { + String encoding = Objects.toString(outputEncoding, "UTF-8"); + DependencyUtil.write(output, outputFile, appendOutput, encoding); } } - } - catch ( IOException | ArtifactFilterException | ArtifactResolverException | DependencyResolverException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException | ArtifactFilterException | ArtifactResolverException | DependencyResolverException e) { + throw new MojoExecutionException(e.getMessage(), e); } } @@ -159,23 +135,20 @@ protected void doExecute() * @throws ArtifactFilterException in case of an error * @throws ArtifactResolverException in case of an error */ - protected Set resolvePluginArtifacts() - throws ArtifactFilterException, ArtifactResolverException - { + protected Set resolvePluginArtifacts() throws ArtifactFilterException, ArtifactResolverException { final Set plugins = getProject().getPluginArtifacts(); final Set reports = getProject().getReportArtifacts(); Set artifacts = new LinkedHashSet<>(); - artifacts.addAll( reports ); - artifacts.addAll( plugins ); + artifacts.addAll(reports); + artifacts.addAll(plugins); final FilterArtifacts filter = getArtifactsFilter(); - artifacts = filter.filter( artifacts ); + artifacts = filter.filter(artifacts); - Set resolvedArtifacts = new LinkedHashSet<>( artifacts.size() ); + Set resolvedArtifacts = new LinkedHashSet<>(artifacts.size()); // final ArtifactFilter filter = getPluginFilter(); - for ( final Artifact artifact : new LinkedHashSet<>( artifacts ) ) - { + for (final Artifact artifact : new LinkedHashSet<>(artifacts)) { // if ( !filter.include( artifact ) ) // { // final String logStr = @@ -193,14 +166,15 @@ protected Set resolvePluginArtifacts() ProjectBuildingRequest buildingRequest = newResolvePluginProjectBuildingRequest(); // resolve the new artifact - resolvedArtifacts.add( getArtifactResolver().resolveArtifact( buildingRequest, artifact ).getArtifact() ); + resolvedArtifacts.add(getArtifactResolver() + .resolveArtifact(buildingRequest, artifact) + .getArtifact()); } return artifacts; } @Override - protected ArtifactsFilter getMarkedArtifactFilter() - { + protected ArtifactsFilter getMarkedArtifactFilter() { return null; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/AbstractSerializingVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/AbstractSerializingVisitor.java index d71f70e2f..8f8f40ed8 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/AbstractSerializingVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/AbstractSerializingVisitor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; import java.io.PrintWriter; import java.io.Writer; @@ -27,8 +26,7 @@ * * @author Jerome Creignou */ -public abstract class AbstractSerializingVisitor -{ +public abstract class AbstractSerializingVisitor { /** * The writer to serialize to. @@ -43,15 +41,11 @@ public abstract class AbstractSerializingVisitor * * @param writer the writer to serialize to. */ - public AbstractSerializingVisitor( Writer writer ) - { - if ( writer instanceof PrintWriter ) - { + public AbstractSerializingVisitor(Writer writer) { + if (writer instanceof PrintWriter) { this.writer = (PrintWriter) writer; - } - else - { - this.writer = new PrintWriter( writer, true ); + } else { + this.writer = new PrintWriter(writer, true); } } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/BuildingDependencyNodeVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/BuildingDependencyNodeVisitor.java index ab93c1c0b..7834c50db 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/BuildingDependencyNodeVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/BuildingDependencyNodeVisitor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; import java.util.ArrayList; import java.util.List; import java.util.Stack; - import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Exclusion; import org.apache.maven.shared.dependency.graph.DependencyNode; @@ -34,9 +32,7 @@ * * @author Mark Hobson */ -public class BuildingDependencyNodeVisitor - implements DependencyNodeVisitor -{ +public class BuildingDependencyNodeVisitor implements DependencyNodeVisitor { // fields ----------------------------------------------------------------- /** @@ -59,9 +55,8 @@ public class BuildingDependencyNodeVisitor /** * Creates a dependency node visitor that clones visited nodes into a new dependency tree. */ - public BuildingDependencyNodeVisitor() - { - this( null ); + public BuildingDependencyNodeVisitor() { + this(null); } /** @@ -71,8 +66,7 @@ public BuildingDependencyNodeVisitor() * @param visitor the dependency node visitor to apply on the resultant dependency tree, or null for * none */ - public BuildingDependencyNodeVisitor( DependencyNodeVisitor visitor ) - { + public BuildingDependencyNodeVisitor(DependencyNodeVisitor visitor) { this.visitor = visitor; parentNodes = new Stack(); @@ -84,8 +78,7 @@ public BuildingDependencyNodeVisitor( DependencyNodeVisitor visitor ) * {@inheritDoc} */ @Override - public boolean visit( DependencyNode node ) - { + public boolean visit(DependencyNode node) { // clone the node WrapperNode newNode = new WrapperNode( parentNodes.isEmpty() ? null : parentNodes.peek(), @@ -95,21 +88,17 @@ public boolean visit( DependencyNode node ) node.getVersionConstraint(), node.getOptional(), node.getExclusions(), - node.toNodeString() - ); - newNode.setChildren( new ArrayList() ); + node.toNodeString()); + newNode.setChildren(new ArrayList()); - if ( parentNodes.empty() ) - { + if (parentNodes.empty()) { rootNode = newNode; - } - else - { + } else { DependencyNode parentNode = parentNodes.peek(); - parentNode.getChildren().add( newNode ); + parentNode.getChildren().add(newNode); } - parentNodes.push( newNode ); + parentNodes.push(newNode); return true; } @@ -118,14 +107,12 @@ public boolean visit( DependencyNode node ) * {@inheritDoc} */ @Override - public boolean endVisit( DependencyNode node ) - { + public boolean endVisit(DependencyNode node) { parentNodes.pop(); // apply the visitor to the resultant tree on the last visit - if ( parentNodes.empty() && visitor != null ) - { - rootNode.accept( visitor ); + if (parentNodes.empty() && visitor != null) { + rootNode.accept(visitor); } return true; @@ -138,8 +125,7 @@ public boolean endVisit( DependencyNode node ) * * @return the dependency node visitor, or null for none */ - public DependencyNodeVisitor getDependencyNodeVisitor() - { + public DependencyNodeVisitor getDependencyNodeVisitor() { return visitor; } @@ -148,13 +134,11 @@ public DependencyNodeVisitor getDependencyNodeVisitor() * * @return the root node, or null if the source tree has not yet been visited */ - public DependencyNode getDependencyTree() - { + public DependencyNode getDependencyTree() { return rootNode; } - private static class WrapperNode implements DependencyNode - { + private static class WrapperNode implements DependencyNode { private final Artifact artifact; @@ -174,15 +158,15 @@ private static class WrapperNode implements DependencyNode private final String nodeString; - private WrapperNode( DependencyNode parent, - Artifact artifact, - String premanagedVersion, - String premanagedScope, - String versionConstraint, - Boolean optional, - List exclusions, - String nodeString ) - { + private WrapperNode( + DependencyNode parent, + Artifact artifact, + String premanagedVersion, + String premanagedScope, + String versionConstraint, + Boolean optional, + List exclusions, + String nodeString) { this.artifact = artifact; this.parent = parent; this.premanagedVersion = premanagedVersion; @@ -194,78 +178,64 @@ private WrapperNode( DependencyNode parent, } @Override - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } @Override - public List getChildren() - { + public List getChildren() { return children; } @Override - public boolean accept( DependencyNodeVisitor visitor ) - { - if ( visitor.visit( this ) ) - { - for ( DependencyNode child : getChildren() ) - { - if ( !child.accept( visitor ) ) - { + public boolean accept(DependencyNodeVisitor visitor) { + if (visitor.visit(this)) { + for (DependencyNode child : getChildren()) { + if (!child.accept(visitor)) { break; } } } - return visitor.endVisit( this ); + return visitor.endVisit(this); } @Override - public DependencyNode getParent() - { + public DependencyNode getParent() { return parent; } @Override - public String getPremanagedVersion() - { + public String getPremanagedVersion() { return premanagedVersion; } @Override - public String getPremanagedScope() - { + public String getPremanagedScope() { return premanagedScope; } @Override - public String getVersionConstraint() - { + public String getVersionConstraint() { return versionConstraint; } @Override - public String toNodeString() - { + public String toNodeString() { return nodeString; } @Override - public Boolean getOptional() - { + public Boolean getOptional() { return optional; } @Override - public List getExclusions() - { + public List getExclusions() { return exclusions; } - public void setChildren( List children ) - { + public void setChildren(List children) { this.children = children; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/DOTDependencyNodeVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/DOTDependencyNodeVisitor.java index adf92e3fd..bf4e0a947 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/DOTDependencyNodeVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/DOTDependencyNodeVisitor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.shared.dependency.graph.DependencyNode; -import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor; +package org.apache.maven.plugins.dependency.tree; import java.io.Writer; import java.util.List; +import org.apache.maven.shared.dependency.graph.DependencyNode; +import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor; /** * A dependency node visitor that serializes visited nodes to DOT @@ -32,39 +30,32 @@ * @author Pi Song * @since 2.1 */ -public class DOTDependencyNodeVisitor - extends AbstractSerializingVisitor - implements DependencyNodeVisitor -{ +public class DOTDependencyNodeVisitor extends AbstractSerializingVisitor implements DependencyNodeVisitor { /** * Constructor. * * @param writer the writer to write to. */ - public DOTDependencyNodeVisitor( Writer writer ) - { - super( writer ); + public DOTDependencyNodeVisitor(Writer writer) { + super(writer); } /** * {@inheritDoc} */ @Override - public boolean visit( DependencyNode node ) - { - if ( node.getParent() == null || node.getParent() == node ) - { - writer.write( "digraph \"" + node.toNodeString() + "\" { " + System.lineSeparator() ); + public boolean visit(DependencyNode node) { + if (node.getParent() == null || node.getParent() == node) { + writer.write("digraph \"" + node.toNodeString() + "\" { " + System.lineSeparator()); } // Generate "currentNode -> Child" lines List children = node.getChildren(); - for ( DependencyNode child : children ) - { - writer.println( "\t\"" + node.toNodeString() + "\" -> \"" + child.toNodeString() + "\" ; " ); + for (DependencyNode child : children) { + writer.println("\t\"" + node.toNodeString() + "\" -> \"" + child.toNodeString() + "\" ; "); } return true; @@ -74,13 +65,10 @@ public boolean visit( DependencyNode node ) * {@inheritDoc} */ @Override - public boolean endVisit( DependencyNode node ) - { - if ( node.getParent() == null || node.getParent() == node ) - { - writer.write( " } " ); + public boolean endVisit(DependencyNode node) { + if (node.getParent() == null || node.getParent() == node) { + writer.write(" } "); } return true; } - } diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/GraphmlDependencyNodeVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/GraphmlDependencyNodeVisitor.java index 372dd7360..11f75ff85 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/GraphmlDependencyNodeVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/GraphmlDependencyNodeVisitor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,35 +16,33 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; import java.io.Writer; - import org.apache.maven.shared.dependency.graph.DependencyNode; import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor; /** * A dependency node visitor that serializes visited nodes to a writer using the * graphml format. - * + * * @author Jerome Creignou * @since 2.1 */ -public class GraphmlDependencyNodeVisitor - extends AbstractSerializingVisitor - implements DependencyNodeVisitor -{ +public class GraphmlDependencyNodeVisitor extends AbstractSerializingVisitor implements DependencyNodeVisitor { /** * Graphml xml file header. Define Schema and root element. We also define 2 key as meta data. */ private static final String GRAPHML_HEADER = " " - + "" + System.lineSeparator() - + " " + System.lineSeparator() - + " " + System.lineSeparator() - + "" + System.lineSeparator(); + + "" + System.lineSeparator() + + " " + System.lineSeparator() + + " " + System.lineSeparator() + + "" + System.lineSeparator(); /** * Graphml xml file footer. @@ -58,32 +54,26 @@ public class GraphmlDependencyNodeVisitor * * @param writer the writer to write to. */ - public GraphmlDependencyNodeVisitor( Writer writer ) - { - super( writer ); + public GraphmlDependencyNodeVisitor(Writer writer) { + super(writer); } /** * {@inheritDoc} */ @Override - public boolean endVisit( DependencyNode node ) - { - if ( node.getParent() == null || node.getParent() == node ) - { - writer.write( GRAPHML_FOOTER ); - } - else - { + public boolean endVisit(DependencyNode node) { + if (node.getParent() == null || node.getParent() == node) { + writer.write(GRAPHML_FOOTER); + } else { DependencyNode p = node.getParent(); - writer.print( "" ); - if ( node.getArtifact().getScope() != null ) - { + writer.print(""); + if (node.getArtifact().getScope() != null) { // add Edge label - writer.print( "" + node.getArtifact().getScope() - + "" ); + writer.print("" + + node.getArtifact().getScope() + ""); } - writer.println( "" ); + writer.println(""); } return true; } @@ -92,18 +82,16 @@ public boolean endVisit( DependencyNode node ) * {@inheritDoc} */ @Override - public boolean visit( DependencyNode node ) - { - if ( node.getParent() == null || node.getParent() == node ) - { - writer.write( GRAPHML_HEADER ); + public boolean visit(DependencyNode node) { + if (node.getParent() == null || node.getParent() == node) { + writer.write(GRAPHML_HEADER); } // write node - writer.print( "" ); + writer.print(""); // add node label - writer.print( "" + node.toNodeString() - + "" ); - writer.println( "" ); + writer.print("" + node.toNodeString() + + ""); + writer.println(""); return true; } @@ -116,8 +104,7 @@ public boolean visit( DependencyNode node ) * @param node the DependencyNode to use. * @return the unique id. */ - private static String generateId( DependencyNode node ) - { - return String.valueOf( node.hashCode() ); + private static String generateId(DependencyNode node) { + return String.valueOf(node.hashCode()); } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/TGFDependencyNodeVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/TGFDependencyNodeVisitor.java index 80c634876..c76fdb984 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/TGFDependencyNodeVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/TGFDependencyNodeVisitor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; import java.io.Writer; import java.util.ArrayList; import java.util.List; - import org.apache.maven.shared.dependency.graph.DependencyNode; import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor; @@ -33,18 +31,14 @@ * @author Jerome Creignou * @since 2.1 */ -public class TGFDependencyNodeVisitor - extends AbstractSerializingVisitor - implements DependencyNodeVisitor -{ +public class TGFDependencyNodeVisitor extends AbstractSerializingVisitor implements DependencyNodeVisitor { /** * Utiity class to write an Edge. * * @author Jerome Creignou */ - static final class EdgeAppender - { + static final class EdgeAppender { /** * Edge start. */ @@ -67,8 +61,7 @@ static final class EdgeAppender * @param to edge end * @param label optional label. */ - EdgeAppender( DependencyNode from, DependencyNode to, String label ) - { + EdgeAppender(DependencyNode from, DependencyNode to, String label) { super(); this.from = from; this.to = to; @@ -79,17 +72,14 @@ static final class EdgeAppender * build a string representing the edge. */ @Override - public String toString() - { - StringBuilder result = new StringBuilder( generateId( from ) ); - result.append( ' ' ).append( generateId( to ) ); - if ( label != null ) - { - result.append( ' ' ).append( label ); + public String toString() { + StringBuilder result = new StringBuilder(generateId(from)); + result.append(' ').append(generateId(to)); + if (label != null) { + result.append(' ').append(label); } return result.toString(); } - } /** @@ -102,31 +92,25 @@ public String toString() * * @param writer the writer to write to. */ - public TGFDependencyNodeVisitor( Writer writer ) - { - super( writer ); + public TGFDependencyNodeVisitor(Writer writer) { + super(writer); } /** * {@inheritDoc} */ @Override - public boolean endVisit( DependencyNode node ) - { - if ( node.getParent() == null || node.getParent() == node ) - { + public boolean endVisit(DependencyNode node) { + if (node.getParent() == null || node.getParent() == node) { // dump edges on last node endVisit - writer.println( "#" ); - for ( EdgeAppender edge : edges ) - { - writer.println( edge.toString() ); + writer.println("#"); + for (EdgeAppender edge : edges) { + writer.println(edge.toString()); } - } - else - { + } else { DependencyNode p = node.getParent(); // using scope as edge label. - edges.add( new EdgeAppender( p, node, node.getArtifact().getScope() ) ); + edges.add(new EdgeAppender(p, node, node.getArtifact().getScope())); } return true; } @@ -135,12 +119,11 @@ public boolean endVisit( DependencyNode node ) * {@inheritDoc} */ @Override - public boolean visit( DependencyNode node ) - { + public boolean visit(DependencyNode node) { // write node - writer.write( generateId( node ) ); - writer.write( " " ); - writer.println( node.toNodeString() ); + writer.write(generateId(node)); + writer.write(" "); + writer.println(node.toNodeString()); return true; } @@ -153,8 +136,7 @@ public boolean visit( DependencyNode node ) * @param node the DependencyNode to use. * @return the unique id. */ - private static String generateId( DependencyNode node ) - { - return String.valueOf( node.hashCode() ); + private static String generateId(DependencyNode node) { + return String.valueOf(node.hashCode()); } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java b/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java index 6bd0397e4..ac1131242 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -56,15 +63,6 @@ import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - /** * Displays the dependency tree for this project. Multiple formats are supported: text (by default), but also * DOT, @@ -74,58 +72,56 @@ * @author Mark Hobson * @since 2.0-alpha-5 */ -@Mojo( name = "tree", requiresDependencyCollection = ResolutionScope.TEST, threadSafe = true ) -public class TreeMojo - extends AbstractMojo -{ +@Mojo(name = "tree", requiresDependencyCollection = ResolutionScope.TEST, threadSafe = true) +public class TreeMojo extends AbstractMojo { // fields ----------------------------------------------------------------- /** * The Maven project. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; - - @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) + + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") private String outputEncoding; /** * Contains the full list of projects in the reactor. */ - @Parameter( defaultValue = "${reactorProjects}", readonly = true, required = true ) + @Parameter(defaultValue = "${reactorProjects}", readonly = true, required = true) private List reactorProjects; @Component private RepositorySystem repositorySystem; - @Parameter ( defaultValue = "${repositorySystem}" ) + @Parameter(defaultValue = "${repositorySystem}") RepositorySystem repositorySystemParam; /** * The current repository/network configuration of Maven. */ - @Parameter( defaultValue = "${repositorySystemSession}" ) + @Parameter(defaultValue = "${repositorySystemSession}") private RepositorySystemSession repoSession; /** * The project's remote repositories to use for the resolution of project dependencies. */ - @Parameter( defaultValue = "${project.remoteProjectRepositories}" ) + @Parameter(defaultValue = "${project.remoteProjectRepositories}") private List projectRepos; /** * The dependency collector builder to use. */ - @Component( hint = "default" ) + @Component(hint = "default") private DependencyCollectorBuilder dependencyCollectorBuilder; /** * The dependency graph builder to use. */ - @Component( hint = "default" ) + @Component(hint = "default") private DependencyGraphBuilder dependencyGraphBuilder; /** @@ -134,7 +130,7 @@ public class TreeMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "outputFile" ) + @Parameter(property = "outputFile") private File outputFile; /** @@ -144,7 +140,7 @@ public class TreeMojo * * @since 2.2 */ - @Parameter( property = "outputType", defaultValue = "text" ) + @Parameter(property = "outputType", defaultValue = "text") private String outputType; /** @@ -153,7 +149,7 @@ public class TreeMojo * * @since 2.0-alpha-5 */ - @Parameter( property = "scope" ) + @Parameter(property = "scope") private String scope; /** @@ -161,7 +157,7 @@ public class TreeMojo * * @since 2.0-alpha-6 */ - @Parameter( property = "verbose", defaultValue = "false" ) + @Parameter(property = "verbose", defaultValue = "false") private boolean verbose; /** @@ -171,38 +167,38 @@ public class TreeMojo * * @since 2.0-alpha-6 */ - @Parameter( property = "tokens", defaultValue = "standard" ) + @Parameter(property = "tokens", defaultValue = "standard") private String tokens; /** * A comma-separated list of artifacts to filter the serialized dependency tree by, or null not to * filter the dependency tree. The filter syntax is: - * + * *
          * [groupId]:[artifactId]:[type]:[version]
          * 
    - * + * * where each pattern segment is optional and supports full and partial * wildcards. An empty pattern * segment is treated as an implicit wildcard. *

    * For example, org.apache.* will match all artifacts whose group id starts with * org.apache., and :::*-SNAPSHOT will match all snapshot artifacts. *

    - * + * * @see StrictPatternIncludesArtifactFilter * @since 2.0-alpha-6 */ - @Parameter( property = "includes" ) + @Parameter(property = "includes") private String includes; /** * A comma-separated list of artifacts to filter from the serialized dependency tree, or null not to * filter any artifacts from the dependency tree. The filter syntax is: - * + * *
          * [groupId]:[artifactId]:[type]:[version]
          * 
    - * + * * where each pattern segment is optional and supports full and partial * wildcards. An empty pattern * segment is treated as an implicit wildcard. *

    @@ -213,7 +209,7 @@ public class TreeMojo * @see StrictPatternExcludesArtifactFilter * @since 2.0-alpha-6 */ - @Parameter( property = "excludes" ) + @Parameter(property = "excludes") private String excludes; /** @@ -226,7 +222,7 @@ public class TreeMojo * * @since 2.2 */ - @Parameter( property = "appendOutput", defaultValue = "false" ) + @Parameter(property = "appendOutput", defaultValue = "false") private boolean appendOutput; /** @@ -234,7 +230,7 @@ public class TreeMojo * * @since 2.7 */ - @Parameter( property = "skip", defaultValue = "false" ) + @Parameter(property = "skip", defaultValue = "false") private boolean skip; // Mojo methods ----------------------------------------------------------- @@ -242,60 +238,46 @@ public class TreeMojo * @see org.apache.maven.plugin.Mojo#execute() */ @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { - getLog().info( "Skipping plugin execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { + getLog().info("Skipping plugin execution"); return; } - try - { + try { String dependencyTreeString; // TODO: note that filter does not get applied due to MSHARED-4 ArtifactFilter artifactFilter = createResolvingArtifactFilter(); ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); + new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); - buildingRequest.setProject( project ); + buildingRequest.setProject(project); - if ( verbose ) - { - rootNode = dependencyCollectorBuilder.collectDependencyGraph( buildingRequest, artifactFilter ); - dependencyTreeString = serializeDependencyTree( rootNode ); - } - else - { + if (verbose) { + rootNode = dependencyCollectorBuilder.collectDependencyGraph(buildingRequest, artifactFilter); + dependencyTreeString = serializeDependencyTree(rootNode); + } else { // non-verbose mode use dependency graph component, which gives consistent results with Maven version // running - rootNode = dependencyGraphBuilder.buildDependencyGraph( buildingRequest, artifactFilter ); + rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, artifactFilter); - dependencyTreeString = serializeDependencyTree( rootNode ); + dependencyTreeString = serializeDependencyTree(rootNode); } - if ( outputFile != null ) - { - String encoding = Objects.toString( outputEncoding, "UTF-8" ); - DependencyUtil.write( dependencyTreeString, outputFile, this.appendOutput, encoding ); + if (outputFile != null) { + String encoding = Objects.toString(outputEncoding, "UTF-8"); + DependencyUtil.write(dependencyTreeString, outputFile, this.appendOutput, encoding); - getLog().info( "Wrote dependency tree to: " + outputFile ); - } - else - { - DependencyUtil.log( dependencyTreeString, getLog() ); + getLog().info("Wrote dependency tree to: " + outputFile); + } else { + DependencyUtil.log(dependencyTreeString, getLog()); } - } - catch ( DependencyGraphBuilderException | DependencyCollectorBuilderException exception ) - { - throw new MojoExecutionException( "Cannot build project dependency graph", exception ); - } - catch ( IOException exception ) - { - throw new MojoExecutionException( "Cannot serialize project dependency graph", exception ); + } catch (DependencyGraphBuilderException | DependencyCollectorBuilderException exception) { + throw new MojoExecutionException("Cannot build project dependency graph", exception); + } catch (IOException exception) { + throw new MojoExecutionException("Cannot serialize project dependency graph", exception); } } @@ -306,8 +288,7 @@ public void execute() * * @return the Maven project */ - public MavenProject getProject() - { + public MavenProject getProject() { return project; } @@ -316,24 +297,21 @@ public MavenProject getProject() * * @return the dependency tree root node */ - public DependencyNode getDependencyGraph() - { + public DependencyNode getDependencyGraph() { return rootNode; } /** * @return {@link #skip} */ - public boolean isSkip() - { + public boolean isSkip() { return skip; } /** * @param skip {@link #skip} */ - public void setSkip( boolean skip ) - { + public void setSkip(boolean skip) { this.skip = skip; } @@ -344,19 +322,15 @@ public void setSkip( boolean skip ) * * @return the artifact filter */ - private ArtifactFilter createResolvingArtifactFilter() - { + private ArtifactFilter createResolvingArtifactFilter() { ArtifactFilter filter; // filter scope - if ( scope != null ) - { - getLog().debug( "+ Resolving dependency tree for scope '" + scope + "'" ); + if (scope != null) { + getLog().debug("+ Resolving dependency tree for scope '" + scope + "'"); - filter = new ScopeArtifactFilter( scope ); - } - else - { + filter = new ScopeArtifactFilter(scope); + } else { filter = null; } @@ -369,29 +343,27 @@ private ArtifactFilter createResolvingArtifactFilter() * @param theRootNode the dependency tree root node to serialize * @return the serialized dependency tree */ - private String serializeDependencyTree( DependencyNode theRootNode ) - { + private String serializeDependencyTree(DependencyNode theRootNode) { StringWriter writer = new StringWriter(); - DependencyNodeVisitor visitor = getSerializingDependencyNodeVisitor( writer ); + DependencyNodeVisitor visitor = getSerializingDependencyNodeVisitor(writer); // TODO: remove the need for this when the serializer can calculate last nodes from visitor calls only - visitor = new BuildingDependencyNodeVisitor( visitor ); + visitor = new BuildingDependencyNodeVisitor(visitor); DependencyNodeFilter filter = createDependencyNodeFilter(); - if ( filter != null ) - { + if (filter != null) { CollectingDependencyNodeVisitor collectingVisitor = new CollectingDependencyNodeVisitor(); - DependencyNodeVisitor firstPassVisitor = new FilteringDependencyNodeVisitor( collectingVisitor, filter ); - theRootNode.accept( firstPassVisitor ); + DependencyNodeVisitor firstPassVisitor = new FilteringDependencyNodeVisitor(collectingVisitor, filter); + theRootNode.accept(firstPassVisitor); DependencyNodeFilter secondPassFilter = - new AncestorOrSelfDependencyNodeFilter( collectingVisitor.getNodes() ); - visitor = new FilteringDependencyNodeVisitor( visitor, secondPassFilter ); + new AncestorOrSelfDependencyNodeFilter(collectingVisitor.getNodes()); + visitor = new FilteringDependencyNodeVisitor(visitor, secondPassFilter); } - theRootNode.accept( visitor ); + theRootNode.accept(visitor); return writer.toString(); } @@ -400,23 +372,15 @@ private String serializeDependencyTree( DependencyNode theRootNode ) * @param writer {@link Writer} * @return {@link DependencyNodeVisitor} */ - public DependencyNodeVisitor getSerializingDependencyNodeVisitor( Writer writer ) - { - if ( "graphml".equals( outputType ) ) - { - return new GraphmlDependencyNodeVisitor( writer ); - } - else if ( "tgf".equals( outputType ) ) - { - return new TGFDependencyNodeVisitor( writer ); - } - else if ( "dot".equals( outputType ) ) - { - return new DOTDependencyNodeVisitor( writer ); - } - else - { - return new SerializingDependencyNodeVisitor( writer, toGraphTokens( tokens ) ); + public DependencyNodeVisitor getSerializingDependencyNodeVisitor(Writer writer) { + if ("graphml".equals(outputType)) { + return new GraphmlDependencyNodeVisitor(writer); + } else if ("tgf".equals(outputType)) { + return new TGFDependencyNodeVisitor(writer); + } else if ("dot".equals(outputType)) { + return new DOTDependencyNodeVisitor(writer); + } else { + return new SerializingDependencyNodeVisitor(writer, toGraphTokens(tokens)); } } @@ -426,24 +390,18 @@ else if ( "dot".equals( outputType ) ) * @param theTokens the graph tokens name * @return the GraphTokens instance */ - private GraphTokens toGraphTokens( String theTokens ) - { + private GraphTokens toGraphTokens(String theTokens) { GraphTokens graphTokens; - if ( "whitespace".equals( theTokens ) ) - { - getLog().debug( "+ Using whitespace tree tokens" ); + if ("whitespace".equals(theTokens)) { + getLog().debug("+ Using whitespace tree tokens"); graphTokens = SerializingDependencyNodeVisitor.WHITESPACE_TOKENS; - } - else if ( "extended".equals( theTokens ) ) - { - getLog().debug( "+ Using extended tree tokens" ); + } else if ("extended".equals(theTokens)) { + getLog().debug("+ Using extended tree tokens"); graphTokens = SerializingDependencyNodeVisitor.EXTENDED_TOKENS; - } - else - { + } else { graphTokens = SerializingDependencyNodeVisitor.STANDARD_TOKENS; } @@ -455,33 +413,30 @@ else if ( "extended".equals( theTokens ) ) * * @return the dependency node filter, or null if none required */ - private DependencyNodeFilter createDependencyNodeFilter() - { + private DependencyNodeFilter createDependencyNodeFilter() { List filters = new ArrayList<>(); // filter includes - if ( includes != null ) - { - List patterns = Arrays.asList( includes.split( "," ) ); + if (includes != null) { + List patterns = Arrays.asList(includes.split(",")); - getLog().debug( "+ Filtering dependency tree by artifact include patterns: " + patterns ); + getLog().debug("+ Filtering dependency tree by artifact include patterns: " + patterns); - ArtifactFilter artifactFilter = new StrictPatternIncludesArtifactFilter( patterns ); - filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) ); + ArtifactFilter artifactFilter = new StrictPatternIncludesArtifactFilter(patterns); + filters.add(new ArtifactDependencyNodeFilter(artifactFilter)); } // filter excludes - if ( excludes != null ) - { - List patterns = Arrays.asList( excludes.split( "," ) ); + if (excludes != null) { + List patterns = Arrays.asList(excludes.split(",")); - getLog().debug( "+ Filtering dependency tree by artifact exclude patterns: " + patterns ); + getLog().debug("+ Filtering dependency tree by artifact exclude patterns: " + patterns); - ArtifactFilter artifactFilter = new StrictPatternExcludesArtifactFilter( patterns ); - filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) ); + ArtifactFilter artifactFilter = new StrictPatternExcludesArtifactFilter(patterns); + filters.add(new ArtifactDependencyNodeFilter(artifactFilter)); } - return filters.isEmpty() ? null : new AndDependencyNodeFilter( filters ); + return filters.isEmpty() ? null : new AndDependencyNodeFilter(filters); } // following is required because the version handling in maven code @@ -498,25 +453,19 @@ private DependencyNodeFilter createDependencyNodeFilter() * @deprecated This method is unused in this project and will be removed in the future. */ @Deprecated - public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion ) - { + public static boolean containsVersion(VersionRange allowedRange, ArtifactVersion theVersion) { ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion(); - if ( recommendedVersion == null ) - { + if (recommendedVersion == null) { List restrictions = allowedRange.getRestrictions(); - for ( Restriction restriction : restrictions ) - { - if ( restriction.containsVersion( theVersion ) ) - { + for (Restriction restriction : restrictions) { + if (restriction.containsVersion(theVersion)) { return true; } } return false; - } - else - { + } else { // only singular versions ever have a recommendedVersion - return recommendedVersion.compareTo( theVersion ) <= 0; + return recommendedVersion.compareTo(theVersion) <= 0; } } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/DependencySilentLog.java b/src/main/java/org/apache/maven/plugins/dependency/utils/DependencySilentLog.java index 357b728e6..165a327d0 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/DependencySilentLog.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/DependencySilentLog.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,34 +7,32 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils; import org.apache.maven.plugin.logging.Log; import org.codehaus.plexus.logging.Logger; /** * This logger implements both types of logs currently in use and turns off logs. - * + * * @author Brian Fox */ -public class DependencySilentLog - implements Log, Logger -{ +public class DependencySilentLog implements Log, Logger { /** * @return false * @see org.apache.maven.plugin.logging.Log#isDebugEnabled() */ @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } @@ -46,8 +42,7 @@ public boolean isDebugEnabled() * @see org.apache.maven.plugin.logging.Log#debug(java.lang.CharSequence) */ @Override - public void debug( CharSequence content ) - { + public void debug(CharSequence content) { // nop } @@ -57,8 +52,7 @@ public void debug( CharSequence content ) * @see org.apache.maven.plugin.logging.Log#debug(java.lang.CharSequence, java.lang.Throwable) */ @Override - public void debug( CharSequence content, Throwable error ) - { + public void debug(CharSequence content, Throwable error) { // nop } @@ -68,8 +62,7 @@ public void debug( CharSequence content, Throwable error ) * @see org.apache.maven.plugin.logging.Log#debug(java.lang.Throwable) */ @Override - public void debug( Throwable error ) - { + public void debug(Throwable error) { // nop } @@ -78,8 +71,7 @@ public void debug( Throwable error ) * @see org.apache.maven.plugin.logging.Log#isInfoEnabled() */ @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } @@ -89,8 +81,7 @@ public boolean isInfoEnabled() * @see org.apache.maven.plugin.logging.Log#info(java.lang.CharSequence) */ @Override - public void info( CharSequence content ) - { + public void info(CharSequence content) { // nop } @@ -100,8 +91,7 @@ public void info( CharSequence content ) * @see org.apache.maven.plugin.logging.Log#info(java.lang.CharSequence, java.lang.Throwable) */ @Override - public void info( CharSequence content, Throwable error ) - { + public void info(CharSequence content, Throwable error) { // nop } @@ -111,8 +101,7 @@ public void info( CharSequence content, Throwable error ) * @see org.apache.maven.plugin.logging.Log#info(java.lang.Throwable) */ @Override - public void info( Throwable error ) - { + public void info(Throwable error) { // nop } @@ -122,8 +111,7 @@ public void info( Throwable error ) * @see org.apache.maven.plugin.logging.Log#isWarnEnabled() */ @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { // nop return false; } @@ -134,8 +122,7 @@ public boolean isWarnEnabled() * @see org.apache.maven.plugin.logging.Log#warn(java.lang.CharSequence) */ @Override - public void warn( CharSequence content ) - { + public void warn(CharSequence content) { // nop } @@ -145,8 +132,7 @@ public void warn( CharSequence content ) * @see org.apache.maven.plugin.logging.Log#warn(java.lang.CharSequence, java.lang.Throwable) */ @Override - public void warn( CharSequence content, Throwable error ) - { + public void warn(CharSequence content, Throwable error) { // nop } @@ -156,8 +142,7 @@ public void warn( CharSequence content, Throwable error ) * @see org.apache.maven.plugin.logging.Log#warn(java.lang.Throwable) */ @Override - public void warn( Throwable error ) - { + public void warn(Throwable error) { // nop } @@ -166,8 +151,7 @@ public void warn( Throwable error ) * @see org.apache.maven.plugin.logging.Log#isErrorEnabled() */ @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } @@ -177,8 +161,7 @@ public boolean isErrorEnabled() * @see org.apache.maven.plugin.logging.Log#error(java.lang.CharSequence) */ @Override - public void error( CharSequence content ) - { + public void error(CharSequence content) { // nop } @@ -188,8 +171,7 @@ public void error( CharSequence content ) * @see org.apache.maven.plugin.logging.Log#error(java.lang.CharSequence, java.lang.Throwable) */ @Override - public void error( CharSequence content, Throwable error ) - { + public void error(CharSequence content, Throwable error) { // nop } @@ -199,8 +181,7 @@ public void error( CharSequence content, Throwable error ) * @see org.apache.maven.plugin.logging.Log#error(java.lang.Throwable) */ @Override - public void error( Throwable error ) - { + public void error(Throwable error) { // nop } @@ -210,8 +191,7 @@ public void error( Throwable error ) * @see org.codehaus.plexus.logging.Logger#debug(java.lang.String) */ @Override - public void debug( String message ) - { + public void debug(String message) { // nop } @@ -221,8 +201,7 @@ public void debug( String message ) * @see org.codehaus.plexus.logging.Logger#debug(java.lang.String, java.lang.Throwable) */ @Override - public void debug( String message, Throwable throwable ) - { + public void debug(String message, Throwable throwable) { // nop } @@ -232,8 +211,7 @@ public void debug( String message, Throwable throwable ) * @see org.codehaus.plexus.logging.Logger#info(java.lang.String) */ @Override - public void info( String message ) - { + public void info(String message) { // nop } @@ -243,8 +221,7 @@ public void info( String message ) * @see org.codehaus.plexus.logging.Logger#info(java.lang.String, java.lang.Throwable) */ @Override - public void info( String message, Throwable throwable ) - { + public void info(String message, Throwable throwable) { // nop } @@ -254,8 +231,7 @@ public void info( String message, Throwable throwable ) * @see org.codehaus.plexus.logging.Logger#warn(java.lang.String) */ @Override - public void warn( String message ) - { + public void warn(String message) { // nop } @@ -265,8 +241,7 @@ public void warn( String message ) * @see org.codehaus.plexus.logging.Logger#warn(java.lang.String, java.lang.Throwable) */ @Override - public void warn( String message, Throwable throwable ) - { + public void warn(String message, Throwable throwable) { // nop } @@ -276,8 +251,7 @@ public void warn( String message, Throwable throwable ) * @see org.codehaus.plexus.logging.Logger#error(java.lang.String) */ @Override - public void error( String message ) - { + public void error(String message) { // nop } @@ -287,8 +261,7 @@ public void error( String message ) * @see org.codehaus.plexus.logging.Logger#error(java.lang.String, java.lang.Throwable) */ @Override - public void error( String message, Throwable throwable ) - { + public void error(String message, Throwable throwable) { // nop } @@ -298,8 +271,7 @@ public void error( String message, Throwable throwable ) * @see org.codehaus.plexus.logging.Logger#fatalError(java.lang.String) */ @Override - public void fatalError( String message ) - { + public void fatalError(String message) { // nop } @@ -309,8 +281,7 @@ public void fatalError( String message ) * @see org.codehaus.plexus.logging.Logger#fatalError(java.lang.String, java.lang.Throwable) */ @Override - public void fatalError( String message, Throwable throwable ) - { + public void fatalError(String message, Throwable throwable) { // nop } @@ -319,8 +290,7 @@ public void fatalError( String message, Throwable throwable ) * @see org.codehaus.plexus.logging.Logger#isFatalErrorEnabled() */ @Override - public boolean isFatalErrorEnabled() - { + public boolean isFatalErrorEnabled() { return false; } @@ -329,8 +299,7 @@ public boolean isFatalErrorEnabled() * @see org.codehaus.plexus.logging.Logger#getChildLogger(java.lang.String) */ @Override - public Logger getChildLogger( String name ) - { + public Logger getChildLogger(String name) { return null; } @@ -339,8 +308,7 @@ public Logger getChildLogger( String name ) * @see org.codehaus.plexus.logging.Logger#getThreshold() */ @Override - public int getThreshold() - { + public int getThreshold() { return 0; } @@ -348,8 +316,7 @@ public int getThreshold() * By default, do nothing */ @Override - public void setThreshold( int threshold ) - { + public void setThreshold(int threshold) { // nop } @@ -358,8 +325,7 @@ public void setThreshold( int threshold ) * @see org.codehaus.plexus.logging.Logger#getName() */ @Override - public String getName() - { + public String getName() { return null; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyStatusSets.java b/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyStatusSets.java index 40b6750da..07c7fa3f1 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyStatusSets.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyStatusSets.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,17 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; /** * @author Brian Fox */ -public class DependencyStatusSets -{ +public class DependencyStatusSets { Set resolvedDependencies = null; Set unResolvedDependencies = null; @@ -38,51 +35,39 @@ public class DependencyStatusSets /** * Default ctor. */ - public DependencyStatusSets() - { - - } + public DependencyStatusSets() {} /** * @param resolved set of {@link Artifact} * @param unResolved set of {@link Artifact} * @param skipped set of {@link Artifact} */ - public DependencyStatusSets( Set resolved, Set unResolved, Set skipped ) - { - if ( resolved != null ) - { - this.resolvedDependencies = new LinkedHashSet<>( resolved ); + public DependencyStatusSets(Set resolved, Set unResolved, Set skipped) { + if (resolved != null) { + this.resolvedDependencies = new LinkedHashSet<>(resolved); } - if ( unResolved != null ) - { - this.unResolvedDependencies = new LinkedHashSet<>( unResolved ); + if (unResolved != null) { + this.unResolvedDependencies = new LinkedHashSet<>(unResolved); } - if ( skipped != null ) - { - this.skippedDependencies = new LinkedHashSet<>( skipped ); + if (skipped != null) { + this.skippedDependencies = new LinkedHashSet<>(skipped); } } /** * @return Returns the resolvedDependencies. */ - public Set getResolvedDependencies() - { + public Set getResolvedDependencies() { return this.resolvedDependencies; } /** * @param resolvedDependencies The resolvedDependencies to set. */ - public void setResolvedDependencies( Set resolvedDependencies ) - { - if ( resolvedDependencies != null ) - { - this.resolvedDependencies = new LinkedHashSet<>( resolvedDependencies ); - } - else - { + public void setResolvedDependencies(Set resolvedDependencies) { + if (resolvedDependencies != null) { + this.resolvedDependencies = new LinkedHashSet<>(resolvedDependencies); + } else { this.resolvedDependencies = null; } } @@ -90,22 +75,17 @@ public void setResolvedDependencies( Set resolvedDependencies ) /** * @return Returns the skippedDependencies. */ - public Set getSkippedDependencies() - { + public Set getSkippedDependencies() { return this.skippedDependencies; } /** * @param skippedDependencies The skippedDependencies to set. */ - public void setSkippedDependencies( Set skippedDependencies ) - { - if ( skippedDependencies != null ) - { - this.skippedDependencies = new LinkedHashSet<>( skippedDependencies ); - } - else - { + public void setSkippedDependencies(Set skippedDependencies) { + if (skippedDependencies != null) { + this.skippedDependencies = new LinkedHashSet<>(skippedDependencies); + } else { this.skippedDependencies = null; } } @@ -113,22 +93,17 @@ public void setSkippedDependencies( Set skippedDependencies ) /** * @return Returns the unResolvedDependencies. */ - public Set getUnResolvedDependencies() - { + public Set getUnResolvedDependencies() { return this.unResolvedDependencies; } /** * @param unResolvedDependencies The unResolvedDependencies to set. */ - public void setUnResolvedDependencies( Set unResolvedDependencies ) - { - if ( unResolvedDependencies != null ) - { - this.unResolvedDependencies = new LinkedHashSet<>( unResolvedDependencies ); - } - else - { + public void setUnResolvedDependencies(Set unResolvedDependencies) { + if (unResolvedDependencies != null) { + this.unResolvedDependencies = new LinkedHashSet<>(unResolvedDependencies); + } else { this.unResolvedDependencies = null; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyUtil.java b/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyUtil.java index 6639c04a8..2c7c2c2a0 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyUtil.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/DependencyUtil.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils; import java.io.BufferedReader; import java.io.File; @@ -27,7 +26,6 @@ import java.io.StringReader; import java.io.Writer; import java.util.Objects; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.plugin.logging.Log; @@ -35,63 +33,59 @@ /** * Utility class with static helper methods. - * + * * @author Brian Fox */ -public final class DependencyUtil -{ +public final class DependencyUtil { /** * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the artifactId, * Classifier (if used) and Type. Otherwise, this method returns the artifact file name. - * + * * @param artifact File to be formatted. * @param removeVersion Specifies if the version should be removed from the file name. * @return Formatted file name in the format artifactId-[version]-[classifier].[type] * @see #getFormattedFileName(Artifact, boolean, boolean) */ - public static String getFormattedFileName( Artifact artifact, boolean removeVersion ) - { - return getFormattedFileName( artifact, removeVersion, false ); + public static String getFormattedFileName(Artifact artifact, boolean removeVersion) { + return getFormattedFileName(artifact, removeVersion, false); } /** * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the groupId (if * prependGroupId is true) artifactId, Classifier (if used) and Type. Otherwise, this method returns the * artifact file name. - * + * * @param artifact File to be formatted. * @param removeVersion Specifies if the version should be removed from the file name. * @param prependGroupId Specifies if the groupId should be prepended to the file name. * @return Formatted file name in the format [groupId].artifactId-[version]-[classifier].[type] */ - public static String getFormattedFileName( Artifact artifact, boolean removeVersion, boolean prependGroupId ) - { - return getFormattedFileName( artifact, removeVersion, prependGroupId, false ); + public static String getFormattedFileName(Artifact artifact, boolean removeVersion, boolean prependGroupId) { + return getFormattedFileName(artifact, removeVersion, prependGroupId, false); } /** * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the groupId (if * prependGroupId is true) artifactId, Classifier (if used), and Type. Otherwise, this method returns the * artifact file name. - * + * * @param artifact file to be formatted * @param removeVersion Specifies if the version should be removed from the file name * @param prependGroupId Specifies if the groupId should be prepended to the file name * @param useBaseVersion Specifies if the baseVersion of the artifact should be used instead of the version * @return Formatted file name in the format [groupId].artifactId-[version]-[classifier].[type] */ - public static String getFormattedFileName( Artifact artifact, boolean removeVersion, boolean prependGroupId, - boolean useBaseVersion ) - { - return getFormattedFileName( artifact, removeVersion, prependGroupId, useBaseVersion, false ); + public static String getFormattedFileName( + Artifact artifact, boolean removeVersion, boolean prependGroupId, boolean useBaseVersion) { + return getFormattedFileName(artifact, removeVersion, prependGroupId, useBaseVersion, false); } /** * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the groupId (if * prependGroupId is true) artifactId, Classifier (if used) and Type. Otherwise, this method returns the * artifact file name. - * + * * @param artifact File to be formatted. * @param removeVersion Specifies if the version should be removed from the file name. * @param prependGroupId Specifies if the groupId should be prepended to the file name. @@ -99,49 +93,44 @@ public static String getFormattedFileName( Artifact artifact, boolean removeVers * @param removeClassifier Specifies if the classifier of the artifact should be remved from the file name. * @return Formatted file name in the format [groupId].artifactId-[version]-[classifier].[type] */ - public static String getFormattedFileName( Artifact artifact, boolean removeVersion, boolean prependGroupId, - boolean useBaseVersion, boolean removeClassifier ) - { + public static String getFormattedFileName( + Artifact artifact, + boolean removeVersion, + boolean prependGroupId, + boolean useBaseVersion, + boolean removeClassifier) { StringBuilder destFileName = new StringBuilder(); - if ( prependGroupId ) - { - destFileName.append( artifact.getGroupId() ).append( "." ); + if (prependGroupId) { + destFileName.append(artifact.getGroupId()).append("."); } String versionString; - if ( !removeVersion ) - { - if ( useBaseVersion ) - { - versionString = "-" + ArtifactUtils.toSnapshotVersion( artifact.getVersion() ); - } - else - { + if (!removeVersion) { + if (useBaseVersion) { + versionString = "-" + ArtifactUtils.toSnapshotVersion(artifact.getVersion()); + } else { versionString = "-" + artifact.getVersion(); } - } - else - { + } else { versionString = ""; } String classifierString = ""; - if ( !removeClassifier && StringUtils.isNotEmpty( artifact.getClassifier() ) ) - { + if (!removeClassifier && StringUtils.isNotEmpty(artifact.getClassifier())) { classifierString = "-" + artifact.getClassifier(); } - destFileName.append( artifact.getArtifactId() ).append( versionString ); - destFileName.append( classifierString ).append( "." ); - destFileName.append( artifact.getArtifactHandler().getExtension() ); + destFileName.append(artifact.getArtifactId()).append(versionString); + destFileName.append(classifierString).append("."); + destFileName.append(artifact.getArtifactHandler().getExtension()); return destFileName.toString(); } /** * Formats the outputDirectory based on type. - * + * * @param useSubdirsPerScope if a new sub directory should be used for each scope. * @param useSubdirsPerType if a new sub directory should be used for each type. * @param useSubdirPerArtifact if a new sub directory should be used for each artifact. @@ -153,65 +142,59 @@ public static String getFormattedFileName( Artifact artifact, boolean removeVers * @param artifact information about the artifact. * @return a formatted File object to use for output. */ - public static File getFormattedOutputDirectory( boolean useSubdirsPerScope, boolean useSubdirsPerType, - boolean useSubdirPerArtifact, boolean useRepositoryLayout, - boolean removeVersion, boolean removeType, File outputDirectory, - Artifact artifact ) - { - StringBuilder sb = new StringBuilder( 128 ); - if ( useRepositoryLayout ) - { + public static File getFormattedOutputDirectory( + boolean useSubdirsPerScope, + boolean useSubdirsPerType, + boolean useSubdirPerArtifact, + boolean useRepositoryLayout, + boolean removeVersion, + boolean removeType, + File outputDirectory, + Artifact artifact) { + StringBuilder sb = new StringBuilder(128); + if (useRepositoryLayout) { // group id - sb.append( artifact.getGroupId().replace( '.', File.separatorChar ) ).append( File.separatorChar ); + sb.append(artifact.getGroupId().replace('.', File.separatorChar)).append(File.separatorChar); // artifact id - sb.append( artifact.getArtifactId() ).append( File.separatorChar ); + sb.append(artifact.getArtifactId()).append(File.separatorChar); // version - sb.append( artifact.getBaseVersion() ).append( File.separatorChar ); - } - else - { - if ( useSubdirsPerScope ) - { - sb.append( artifact.getScope() ).append( File.separatorChar ); + sb.append(artifact.getBaseVersion()).append(File.separatorChar); + } else { + if (useSubdirsPerScope) { + sb.append(artifact.getScope()).append(File.separatorChar); } - if ( useSubdirsPerType ) - { - sb.append( artifact.getType() ).append( "s" ).append( File.separatorChar ); + if (useSubdirsPerType) { + sb.append(artifact.getType()).append("s").append(File.separatorChar); } - if ( useSubdirPerArtifact ) - { - String artifactString = getDependencyId( artifact, removeVersion, removeType ); - sb.append( artifactString ).append( File.separatorChar ); + if (useSubdirPerArtifact) { + String artifactString = getDependencyId(artifact, removeVersion, removeType); + sb.append(artifactString).append(File.separatorChar); } } - return new File( outputDirectory, sb.toString() ); + return new File(outputDirectory, sb.toString()); } - private static String getDependencyId( Artifact artifact, boolean removeVersion, boolean removeType ) - { + private static String getDependencyId(Artifact artifact, boolean removeVersion, boolean removeType) { StringBuilder sb = new StringBuilder(); - sb.append( artifact.getArtifactId() ); + sb.append(artifact.getArtifactId()); - if ( !removeVersion ) - { - sb.append( "-" ); - sb.append( artifact.getVersion() ); + if (!removeVersion) { + sb.append("-"); + sb.append(artifact.getVersion()); } - if ( StringUtils.isNotEmpty( artifact.getClassifier() ) ) - { - sb.append( "-" ); - sb.append( artifact.getClassifier() ); + if (StringUtils.isNotEmpty(artifact.getClassifier())) { + sb.append("-"); + sb.append(artifact.getClassifier()); } // if the classifier and type are the same (sources), then don't // repeat. // avoids names like foo-sources-sources - if ( !removeType && !Objects.equals( artifact.getClassifier(), artifact.getType() ) ) - { - sb.append( "-" ); - sb.append( artifact.getType() ); + if (!removeType && !Objects.equals(artifact.getClassifier(), artifact.getType())) { + sb.append("-"); + sb.append(artifact.getType()); } return sb.toString(); @@ -219,7 +202,7 @@ private static String getDependencyId( Artifact artifact, boolean removeVersion, /** * Writes the specified string to the specified file. - * + * * @param string the string to write * @param file the file to write to * @param append append to existing file or not @@ -228,49 +211,42 @@ private static String getDependencyId( Artifact artifact, boolean removeVersion, * @deprecated specify an encoding instead of a log */ @Deprecated - public static synchronized void write( String string, File file, boolean append, Log log ) - throws IOException - { - write( string, file, append, "UTF-8" ); + public static synchronized void write(String string, File file, boolean append, Log log) throws IOException { + write(string, file, append, "UTF-8"); } - + /** * Writes the specified string to the specified file. - * + * * @param string the string to write * @param file the file to write to * @param append append to existing file or not * @param encoding character set name * @throws IOException if an I/O error occurs */ - public static synchronized void write( String string, File file, boolean append, String encoding ) - throws IOException - { - file.getParentFile().mkdirs(); + public static synchronized void write(String string, File file, boolean append, String encoding) + throws IOException { + file.getParentFile().mkdirs(); - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file, append ), encoding ) ) - { - writer.write( string ); + try (Writer writer = new OutputStreamWriter(new FileOutputStream(file, append), encoding)) { + writer.write(string); } } /** * Writes the specified string to the log at info level. - * + * * @param string the string to write * @param log where to log information * @throws IOException if an I/O error occurs */ - public static synchronized void log( String string, Log log ) - throws IOException - { - BufferedReader reader = new BufferedReader( new StringReader( string ) ); + public static synchronized void log(String string, Log log) throws IOException { + BufferedReader reader = new BufferedReader(new StringReader(string)); String line; - while ( ( line = reader.readLine() ) != null ) - { - log.info( line ); + while ((line = reader.readLine()) != null) { + log.info(line); } reader.close(); @@ -278,28 +254,25 @@ public static synchronized void log( String string, Log log ) /** * Mainly used to parse excludes, includes configuration. - * + * * @param str the string to split * @return the result items */ - public static String[] tokenizer( String str ) - { - return StringUtils.split( cleanToBeTokenizedString( str ), "," ); + public static String[] tokenizer(String str) { + return StringUtils.split(cleanToBeTokenizedString(str), ","); } /** * Clean up configuration string before it can be tokenized. - * + * * @param str the string which should be cleaned * @return cleaned up string */ - public static String cleanToBeTokenizedString( String str ) - { + public static String cleanToBeTokenizedString(String str) { String ret = ""; - if ( !StringUtils.isEmpty( str ) ) - { + if (!StringUtils.isEmpty(str)) { // remove initial and ending spaces, plus all spaces next to commas - ret = str.trim().replaceAll( "[\\s]*,[\\s]*", "," ); + ret = str.trim().replaceAll("[\\s]*,[\\s]*", ","); } return ret; diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ArtifactItemFilter.java b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ArtifactItemFilter.java index 0ce5eea22..a6880e626 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ArtifactItemFilter.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ArtifactItemFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.filters; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,15 +7,16 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; @@ -25,14 +24,12 @@ /** * @author Brian Fox */ -public interface ArtifactItemFilter -{ +public interface ArtifactItemFilter { /** * @param item {@link ArtifactItem} * @return true/false. * @throws ArtifactFilterException in case of an error. */ - boolean isArtifactIncluded( ArtifactItem item ) - throws ArtifactFilterException; + boolean isArtifactIncluded(ArtifactItem item) throws ArtifactFilterException; } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/DestFileFilter.java b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/DestFileFilter.java index f2a284827..4c4bbbfdc 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/DestFileFilter.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/DestFileFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.filters; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.LinkedHashSet; +import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; import org.apache.maven.plugins.dependency.utils.DependencyUtil; @@ -26,19 +30,10 @@ import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.codehaus.plexus.util.StringUtils; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.LinkedHashSet; -import java.util.Set; - /** * @author Brian Fox */ -public class DestFileFilter - extends AbstractArtifactsFilter - implements ArtifactItemFilter -{ +public class DestFileFilter extends AbstractArtifactsFilter implements ArtifactItemFilter { private boolean overWriteReleases; private boolean overWriteSnapshots; @@ -68,9 +63,8 @@ public class DestFileFilter /** * @param outputFileDirectory the output directory. */ - public DestFileFilter( File outputFileDirectory ) - { - this( false, false, false, false, false, false, false, false, false, false, outputFileDirectory ); + public DestFileFilter(File outputFileDirectory) { + this(false, false, false, false, false, false, false, false, false, false, outputFileDirectory); } /** @@ -86,11 +80,18 @@ public DestFileFilter( File outputFileDirectory ) * @param useBaseVersion true/false. * @param outputFileDirectory the output directory. */ - public DestFileFilter( boolean overWriteReleases, boolean overWriteSnapshots, boolean overWriteIfNewer, - boolean useSubDirectoryPerArtifact, boolean useSubDirectoryPerType, - boolean useSubDirectoryPerScope, boolean useRepositoryLayout, boolean removeVersion, - boolean prependGroupId, boolean useBaseVersion, File outputFileDirectory ) - { + public DestFileFilter( + boolean overWriteReleases, + boolean overWriteSnapshots, + boolean overWriteIfNewer, + boolean useSubDirectoryPerArtifact, + boolean useSubDirectoryPerType, + boolean useSubDirectoryPerScope, + boolean useRepositoryLayout, + boolean removeVersion, + boolean prependGroupId, + boolean useBaseVersion, + File outputFileDirectory) { this.overWriteReleases = overWriteReleases; this.overWriteSnapshots = overWriteSnapshots; this.overWriteIfNewer = overWriteIfNewer; @@ -110,16 +111,12 @@ public DestFileFilter( boolean overWriteReleases, boolean overWriteSnapshots, bo * org.apache.maven.plugin.logging.Log) */ @Override - public Set filter( Set artifacts ) - throws ArtifactFilterException - { + public Set filter(Set artifacts) throws ArtifactFilterException { Set result = new LinkedHashSet<>(); - for ( Artifact artifact : artifacts ) - { - if ( isArtifactIncluded( new ArtifactItem( artifact ) ) ) - { - result.add( artifact ); + for (Artifact artifact : artifacts) { + if (isArtifactIncluded(new ArtifactItem(artifact))) { + result.add(artifact); } } return result; @@ -128,195 +125,175 @@ public Set filter( Set artifacts ) /** * @return Returns the overWriteReleases. */ - public boolean isOverWriteReleases() - { + public boolean isOverWriteReleases() { return this.overWriteReleases; } /** * @param overWriteReleases The overWriteReleases to set. */ - public void setOverWriteReleases( boolean overWriteReleases ) - { + public void setOverWriteReleases(boolean overWriteReleases) { this.overWriteReleases = overWriteReleases; } /** * @return Returns the overWriteSnapshots. */ - public boolean isOverWriteSnapshots() - { + public boolean isOverWriteSnapshots() { return this.overWriteSnapshots; } /** * @param overWriteSnapshots The overWriteSnapshots to set. */ - public void setOverWriteSnapshots( boolean overWriteSnapshots ) - { + public void setOverWriteSnapshots(boolean overWriteSnapshots) { this.overWriteSnapshots = overWriteSnapshots; } /** * @return Returns the overWriteIfNewer. */ - public boolean isOverWriteIfNewer() - { + public boolean isOverWriteIfNewer() { return this.overWriteIfNewer; } /** * @param overWriteIfNewer The overWriteIfNewer to set. */ - public void setOverWriteIfNewer( boolean overWriteIfNewer ) - { + public void setOverWriteIfNewer(boolean overWriteIfNewer) { this.overWriteIfNewer = overWriteIfNewer; } /** * @return Returns the outputFileDirectory. */ - public File getOutputFileDirectory() - { + public File getOutputFileDirectory() { return this.outputFileDirectory; } /** * @param outputFileDirectory The outputFileDirectory to set. */ - public void setOutputFileDirectory( File outputFileDirectory ) - { + public void setOutputFileDirectory(File outputFileDirectory) { this.outputFileDirectory = outputFileDirectory; } /** * @return Returns the removeVersion. */ - public boolean isRemoveVersion() - { + public boolean isRemoveVersion() { return this.removeVersion; } /** * @param removeType The removeType to set. */ - public void setRemoveType( boolean removeType ) - { + public void setRemoveType(boolean removeType) { this.removeType = removeType; } /** * @return Returns the removeType. */ - public boolean isRemoveType() - { + public boolean isRemoveType() { return this.removeType; } /** * @param removeVersion The removeVersion to set. */ - public void setRemoveVersion( boolean removeVersion ) - { + public void setRemoveVersion(boolean removeVersion) { this.removeVersion = removeVersion; } /** * @return Returns the removeClassifier. */ - public boolean isRemoveClassifier() - { + public boolean isRemoveClassifier() { return this.removeClassifier; } /** * @param removeClassifier The removeClassifier to set. */ - public void setRemoveClassifier( boolean removeClassifier ) - { + public void setRemoveClassifier(boolean removeClassifier) { this.removeClassifier = removeClassifier; } /** * @return Returns the useSubDirectoryPerArtifact. */ - public boolean isUseSubDirectoryPerArtifact() - { + public boolean isUseSubDirectoryPerArtifact() { return this.useSubDirectoryPerArtifact; } /** * @param useSubDirectoryPerArtifact The useSubDirectoryPerArtifact to set. */ - public void setUseSubDirectoryPerArtifact( boolean useSubDirectoryPerArtifact ) - { + public void setUseSubDirectoryPerArtifact(boolean useSubDirectoryPerArtifact) { this.useSubDirectoryPerArtifact = useSubDirectoryPerArtifact; } /** * @return Returns the useSubDirectoryPerType. */ - public boolean isUseSubDirectoryPerType() - { + public boolean isUseSubDirectoryPerType() { return this.useSubDirectoryPerType; } /** * @param useSubDirectoryPerType The useSubDirectoryPerType to set. */ - public void setUseSubDirectoryPerType( boolean useSubDirectoryPerType ) - { + public void setUseSubDirectoryPerType(boolean useSubDirectoryPerType) { this.useSubDirectoryPerType = useSubDirectoryPerType; } /** * @return Returns the useRepositoryLayout */ - public boolean isUseRepositoryLayout() - { + public boolean isUseRepositoryLayout() { return useRepositoryLayout; } /** * @param useRepositoryLayout the useRepositoryLayout to set */ - public void setUseRepositoryLayout( boolean useRepositoryLayout ) - { + public void setUseRepositoryLayout(boolean useRepositoryLayout) { this.useRepositoryLayout = useRepositoryLayout; } @Override - public boolean isArtifactIncluded( ArtifactItem item ) throws ArtifactFilterException - { + public boolean isArtifactIncluded(ArtifactItem item) throws ArtifactFilterException { Artifact artifact = item.getArtifact(); - boolean overWrite = ( artifact.isSnapshot() && this.overWriteSnapshots ) - || ( !artifact.isSnapshot() && this.overWriteReleases ); + boolean overWrite = (artifact.isSnapshot() && this.overWriteSnapshots) + || (!artifact.isSnapshot() && this.overWriteReleases); File destFolder = item.getOutputDirectory(); - if ( destFolder == null ) - { - destFolder = - DependencyUtil.getFormattedOutputDirectory( useSubDirectoryPerScope, useSubDirectoryPerType, - useSubDirectoryPerArtifact, useRepositoryLayout, - removeVersion, removeType, this.outputFileDirectory, - artifact ); + if (destFolder == null) { + destFolder = DependencyUtil.getFormattedOutputDirectory( + useSubDirectoryPerScope, + useSubDirectoryPerType, + useSubDirectoryPerArtifact, + useRepositoryLayout, + removeVersion, + removeType, + this.outputFileDirectory, + artifact); } File destFile; - if ( StringUtils.isEmpty( item.getDestFileName() ) ) - { - String formattedFileName = DependencyUtil.getFormattedFileName( artifact, removeVersion, prependGroupId, - useBaseVersion, removeClassifier ); - destFile = new File( destFolder, formattedFileName ); - } - else - { - destFile = new File( destFolder, item.getDestFileName() ); + if (StringUtils.isEmpty(item.getDestFileName())) { + String formattedFileName = DependencyUtil.getFormattedFileName( + artifact, removeVersion, prependGroupId, useBaseVersion, removeClassifier); + destFile = new File(destFolder, formattedFileName); + } else { + destFile = new File(destFolder, item.getDestFileName()); } - return overWrite || !destFile.exists() || ( overWriteIfNewer && getLastModified( - artifact.getFile() ) > getLastModified( destFile ) ); + return overWrite + || !destFile.exists() + || (overWriteIfNewer && getLastModified(artifact.getFile()) > getLastModified(destFile)); } /** @@ -328,15 +305,11 @@ public boolean isArtifactIncluded( ArtifactItem item ) throws ArtifactFilterExce * @return the last modification time in milliseconds. * @throws ArtifactFilterException in case of a IO Exception. */ - private long getLastModified( File file ) throws ArtifactFilterException - { - try - { - return Files.getLastModifiedTime( file.toPath() ).toMillis(); - } - catch ( IOException e ) - { - throw new ArtifactFilterException( "IO Exception", e ); + private long getLastModified(File file) throws ArtifactFilterException { + try { + return Files.getLastModifiedTime(file.toPath()).toMillis(); + } catch (IOException e) { + throw new ArtifactFilterException("IO Exception", e); } } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/MarkerFileFilter.java b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/MarkerFileFilter.java index 6aa49346c..51fe65fe3 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/MarkerFileFilter.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/MarkerFileFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.filters; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; @@ -32,10 +30,7 @@ /** * @author Brian Fox */ -public class MarkerFileFilter - extends AbstractArtifactsFilter - implements ArtifactItemFilter -{ +public class MarkerFileFilter extends AbstractArtifactsFilter implements ArtifactItemFilter { private boolean overWriteReleases; @@ -54,9 +49,8 @@ public class MarkerFileFilter * @param overWriteIfNewer true/false. * @param handler {@link MarkerHandler} */ - public MarkerFileFilter( boolean overWriteReleases, boolean overWriteSnapshots, boolean overWriteIfNewer, - MarkerHandler handler ) - { + public MarkerFileFilter( + boolean overWriteReleases, boolean overWriteSnapshots, boolean overWriteIfNewer, MarkerHandler handler) { this.overWriteReleases = overWriteReleases; this.overWriteSnapshots = overWriteSnapshots; this.overWriteIfNewer = overWriteIfNewer; @@ -69,16 +63,12 @@ public MarkerFileFilter( boolean overWriteReleases, boolean overWriteSnapshots, * org.apache.maven.plugin.logging.Log) */ @Override - public Set filter( Set artifacts ) - throws ArtifactFilterException - { + public Set filter(Set artifacts) throws ArtifactFilterException { Set result = new LinkedHashSet<>(); - for ( Artifact artifact : artifacts ) - { - if ( isArtifactIncluded( new ArtifactItem( artifact ) ) ) - { - result.add( artifact ); + for (Artifact artifact : artifacts) { + if (isArtifactIncluded(new ArtifactItem(artifact))) { + result.add(artifact); } } @@ -86,71 +76,60 @@ public Set filter( Set artifacts ) } @Override - public boolean isArtifactIncluded( ArtifactItem item ) - throws ArtifactFilterException - { + public boolean isArtifactIncluded(ArtifactItem item) throws ArtifactFilterException { Artifact artifact = item.getArtifact(); - boolean overWrite = ( artifact.isSnapshot() && this.overWriteSnapshots ) - || ( !artifact.isSnapshot() && this.overWriteReleases ); + boolean overWrite = (artifact.isSnapshot() && this.overWriteSnapshots) + || (!artifact.isSnapshot() && this.overWriteReleases); - handler.setArtifact( artifact ); + handler.setArtifact(artifact); - try - { - return overWrite || !handler.isMarkerSet() || ( overWriteIfNewer && handler.isMarkerOlder( artifact ) ); - } - catch ( MojoExecutionException e ) - { - throw new ArtifactFilterException( e.getMessage(), e ); + try { + return overWrite || !handler.isMarkerSet() || (overWriteIfNewer && handler.isMarkerOlder(artifact)); + } catch (MojoExecutionException e) { + throw new ArtifactFilterException(e.getMessage(), e); } } /** * @return Returns the overWriteReleases. */ - public boolean isOverWriteReleases() - { + public boolean isOverWriteReleases() { return this.overWriteReleases; } /** * @param overWriteReleases The overWriteReleases to set. */ - public void setOverWriteReleases( boolean overWriteReleases ) - { + public void setOverWriteReleases(boolean overWriteReleases) { this.overWriteReleases = overWriteReleases; } /** * @return Returns the overWriteSnapshots. */ - public boolean isOverWriteSnapshots() - { + public boolean isOverWriteSnapshots() { return this.overWriteSnapshots; } /** * @param overWriteSnapshots The overWriteSnapshots to set. */ - public void setOverWriteSnapshots( boolean overWriteSnapshots ) - { + public void setOverWriteSnapshots(boolean overWriteSnapshots) { this.overWriteSnapshots = overWriteSnapshots; } /** * @return Returns the overWriteIfNewer. */ - public boolean isOverWriteIfNewer() - { + public boolean isOverWriteIfNewer() { return this.overWriteIfNewer; } /** * @param overWriteIfNewer The overWriteIfNewer to set. */ - public void setOverWriteIfNewer( boolean overWriteIfNewer ) - { + public void setOverWriteIfNewer(boolean overWriteIfNewer) { this.overWriteIfNewer = overWriteIfNewer; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ResolveFileFilter.java b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ResolveFileFilter.java index b321987a1..6225d7e78 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ResolveFileFilter.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/filters/ResolveFileFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.filters; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,15 +7,16 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; @@ -27,30 +26,22 @@ /** * @author Brian Fox */ -public class ResolveFileFilter - extends MarkerFileFilter -{ +public class ResolveFileFilter extends MarkerFileFilter { /** * @param handler {@link MarkerHandler} */ - public ResolveFileFilter( MarkerHandler handler ) - { - super( true, true, true, handler ); + public ResolveFileFilter(MarkerHandler handler) { + super(true, true, true, handler); } @Override - public boolean isArtifactIncluded( ArtifactItem item ) - throws ArtifactFilterException - { - handler.setArtifact( item.getArtifact() ); - try - { - return ( !handler.isMarkerSet() ); - } - catch ( MojoExecutionException e ) - { - throw new ArtifactFilterException( e.getMessage(), e ); + public boolean isArtifactIncluded(ArtifactItem item) throws ArtifactFilterException { + handler.setArtifact(item.getArtifact()); + try { + return (!handler.isMarkerSet()); + } catch (MojoExecutionException e) { + throw new ArtifactFilterException(e.getMessage(), e); } } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/DefaultFileMarkerHandler.java b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/DefaultFileMarkerHandler.java index c6c336450..a8600efef 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/DefaultFileMarkerHandler.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/DefaultFileMarkerHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.markers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,28 +7,26 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; import java.io.File; import java.io.IOException; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; /** * @author Brian Fox */ -public class DefaultFileMarkerHandler - implements MarkerHandler -{ +public class DefaultFileMarkerHandler implements MarkerHandler { /** * The artifact. */ @@ -44,8 +40,7 @@ public class DefaultFileMarkerHandler /** * @param theMarkerFilesDirectory The marker directory. */ - public DefaultFileMarkerHandler( File theMarkerFilesDirectory ) - { + public DefaultFileMarkerHandler(File theMarkerFilesDirectory) { this.markerFilesDirectory = theMarkerFilesDirectory; } @@ -53,25 +48,23 @@ public DefaultFileMarkerHandler( File theMarkerFilesDirectory ) * @param theArtifact {@link Artifact} * @param theMarkerFilesDirectory The marker directory. */ - public DefaultFileMarkerHandler( Artifact theArtifact, File theMarkerFilesDirectory ) - { + public DefaultFileMarkerHandler(Artifact theArtifact, File theMarkerFilesDirectory) { this.artifact = theArtifact; this.markerFilesDirectory = theMarkerFilesDirectory; } /** * Returns properly formatted File - * + * * @return File object for marker. The file is not guaranteed to exist. */ - protected File getMarkerFile() - { - return new File( this.markerFilesDirectory, this.artifact.getId().replace( ':', '-' ) + ".marker" ); + protected File getMarkerFile() { + return new File(this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + ".marker"); } /** * Tests whether the file or directory denoted by this abstract pathname exists. - * + * * @return true if and only if the file or directory denoted by this abstract pathname exists; * false otherwise * @throws SecurityException If a security manager exists and its {@link @@ -79,24 +72,17 @@ protected File getMarkerFile() * directory */ @Override - public boolean isMarkerSet() - throws MojoExecutionException - { + public boolean isMarkerSet() throws MojoExecutionException { File marker = getMarkerFile(); return marker.exists(); } @Override - public boolean isMarkerOlder( Artifact artifact1 ) - throws MojoExecutionException - { + public boolean isMarkerOlder(Artifact artifact1) throws MojoExecutionException { File marker = getMarkerFile(); - if ( marker.exists() ) - { + if (marker.exists()) { return artifact1.getFile().lastModified() > marker.lastModified(); - } - else - { + } else { // if the marker doesn't exist, we want to copy so assume it is // infinitely older return true; @@ -104,66 +90,48 @@ public boolean isMarkerOlder( Artifact artifact1 ) } @Override - public void setMarker() - throws MojoExecutionException - { + public void setMarker() throws MojoExecutionException { File marker = getMarkerFile(); // create marker file - try - { + try { marker.getParentFile().mkdirs(); - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // parent is null, ignore it. } - try - { + try { marker.createNewFile(); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to create Marker: " + marker.getAbsolutePath(), e ); + } catch (IOException e) { + throw new MojoExecutionException("Unable to create Marker: " + marker.getAbsolutePath(), e); } // update marker file timestamp - try - { + try { long ts; - if ( this.artifact != null && this.artifact.getFile() != null ) - { + if (this.artifact != null && this.artifact.getFile() != null) { ts = this.artifact.getFile().lastModified(); - } - else - { + } else { ts = System.currentTimeMillis(); } - if ( !marker.setLastModified( ts ) ) - { - throw new MojoExecutionException( "Unable to update last modified timestamp on marker file " - + marker.getAbsolutePath() ); - + if (!marker.setLastModified(ts)) { + throw new MojoExecutionException( + "Unable to update last modified timestamp on marker file " + marker.getAbsolutePath()); } - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Unable to update Marker timestamp: " + marker.getAbsolutePath(), e ); + } catch (Exception e) { + throw new MojoExecutionException("Unable to update Marker timestamp: " + marker.getAbsolutePath(), e); } } /** * Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the * directory must be empty in order to be deleted. - * + * * @return true if and only if the file or directory is successfully deleted; false * otherwise * @throws SecurityException If a security manager exists and its {@link * java.lang.SecurityManager#checkDelete} method denies delete access to the file */ @Override - public boolean clearMarker() - throws MojoExecutionException - { + public boolean clearMarker() throws MojoExecutionException { File marker = getMarkerFile(); return marker.delete(); } @@ -171,8 +139,7 @@ public boolean clearMarker() /** * @return Returns the artifact. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return this.artifact; } @@ -180,24 +147,21 @@ public Artifact getArtifact() * @param artifact The artifact to set. */ @Override - public void setArtifact( Artifact artifact ) - { + public void setArtifact(Artifact artifact) { this.artifact = artifact; } /** * @return Returns the markerFilesDirectory. */ - public File getMarkerFilesDirectory() - { + public File getMarkerFilesDirectory() { return this.markerFilesDirectory; } /** * @param markerFilesDirectory The markerFilesDirectory to set. */ - public void setMarkerFilesDirectory( File markerFilesDirectory ) - { + public void setMarkerFilesDirectory(File markerFilesDirectory) { this.markerFilesDirectory = markerFilesDirectory; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/MarkerHandler.java b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/MarkerHandler.java index 040c01971..a56aee647 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/MarkerHandler.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/MarkerHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.markers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,15 +7,16 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; @@ -25,39 +24,33 @@ /** * @author Brian Fox */ -public interface MarkerHandler -{ +public interface MarkerHandler { /** * @return true/false. * @throws MojoExecutionException in case of an error. */ - boolean isMarkerSet() - throws MojoExecutionException; + boolean isMarkerSet() throws MojoExecutionException; /** * @throws MojoExecutionException in case of an error. */ - void setMarker() - throws MojoExecutionException; + void setMarker() throws MojoExecutionException; /** * @return true/false. * @throws MojoExecutionException in case of an error. */ - boolean clearMarker() - throws MojoExecutionException; + boolean clearMarker() throws MojoExecutionException; /** * @param artifact {@link Artifact} * @return true/false. * @throws MojoExecutionException in case of an error. */ - boolean isMarkerOlder( Artifact artifact ) - throws MojoExecutionException; + boolean isMarkerOlder(Artifact artifact) throws MojoExecutionException; /** * @param artifact {@link Artifact} */ - void setArtifact( Artifact artifact ); - + void setArtifact(Artifact artifact); } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/SourcesFileMarkerHandler.java b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/SourcesFileMarkerHandler.java index 2134a3c76..4b0d41f31 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/SourcesFileMarkerHandler.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/SourcesFileMarkerHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.markers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,85 +7,76 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; import java.io.File; import java.io.IOException; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; /** * @author Brian Fox */ -public class SourcesFileMarkerHandler - extends DefaultFileMarkerHandler -{ +public class SourcesFileMarkerHandler extends DefaultFileMarkerHandler { boolean resolved; /** * @param markerFilesDirectory the marker files directory. */ - public SourcesFileMarkerHandler( File markerFilesDirectory ) - { - super( markerFilesDirectory ); + public SourcesFileMarkerHandler(File markerFilesDirectory) { + super(markerFilesDirectory); } /** * @param artifact {@link Artifact} * @param markerFilesDirectory marker files directory. * @param isResolved true/false. - */ - public SourcesFileMarkerHandler( Artifact artifact, File markerFilesDirectory, boolean isResolved ) - { - super( artifact, markerFilesDirectory ); + */ + public SourcesFileMarkerHandler(Artifact artifact, File markerFilesDirectory, boolean isResolved) { + super(artifact, markerFilesDirectory); this.resolved = isResolved; } /** * Returns properly formatted File - * + * * @return File object for marker. The file is not guaranteed to exist. */ @Override - public File getMarkerFile() - { - return getMarkerFile( this.resolved ); + public File getMarkerFile() { + return getMarkerFile(this.resolved); } /** * Get MarkerFile, exposed for unit testing purposes - * + * * @param res resolved or not. * @return marker file for this artifact. */ - protected File getMarkerFile( boolean res ) - { + protected File getMarkerFile(boolean res) { String suffix; - if ( res ) - { + if (res) { suffix = ".resolved"; - } - else - { + } else { suffix = ".unresolved"; } - return new File( this.markerFilesDirectory, this.artifact.getId().replace( ':', '-' ) + suffix ); + return new File(this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + suffix); } /** * Tests whether the file or directory denoted by this abstract pathname exists. - * + * * @return true if and only if the file or directory denoted by this abstract pathname exists; * false otherwise * @throws MojoExecutionException If a security manager exists and its {@link @@ -95,34 +84,24 @@ protected File getMarkerFile( boolean res ) * directory */ @Override - public boolean isMarkerSet() - throws MojoExecutionException - { + public boolean isMarkerSet() throws MojoExecutionException { File marker = getMarkerFile(); - File marker2 = getMarkerFile( !this.resolved ); + File marker2 = getMarkerFile(!this.resolved); return marker.exists() || marker2.exists(); } @Override - public boolean isMarkerOlder( Artifact theArtifact ) - throws MojoExecutionException - { + public boolean isMarkerOlder(Artifact theArtifact) throws MojoExecutionException { File marker = getMarkerFile(); - if ( marker.exists() ) - { + if (marker.exists()) { return theArtifact.getFile().lastModified() > marker.lastModified(); - } - else - { - marker = getMarkerFile( !this.resolved ); - if ( marker.exists() ) - { + } else { + marker = getMarkerFile(!this.resolved); + if (marker.exists()) { return theArtifact.getFile().lastModified() > marker.lastModified(); - } - else - { + } else { // if the marker doesn't exist, we want to copy so assume it is // infinitely older return true; @@ -131,56 +110,44 @@ public boolean isMarkerOlder( Artifact theArtifact ) } @Override - public void setMarker() - throws MojoExecutionException - { + public void setMarker() throws MojoExecutionException { File marker = getMarkerFile(); // get the other file if it exists. - File clearMarker = getMarkerFile( !this.resolved ); + File clearMarker = getMarkerFile(!this.resolved); // create marker file - try - { + try { marker.getParentFile().mkdirs(); - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // parent is null, ignore it. } - try - { + try { marker.createNewFile(); // clear the other file if it exists. - if ( clearMarker.exists() ) - { - if ( !clearMarker.delete() ) - { + if (clearMarker.exists()) { + if (!clearMarker.delete()) { clearMarker.deleteOnExit(); } } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to create Marker: " + marker.getAbsolutePath(), e ); + } catch (IOException e) { + throw new MojoExecutionException("Unable to create Marker: " + marker.getAbsolutePath(), e); } } /** * Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the * directory must be empty in order to be deleted. - * + * * @return true if and only if the file or directory is successfully deleted; false * otherwise * @throws SecurityException If a security manager exists and its {@link * java.lang.SecurityManager#checkDelete} method denies delete access to the file */ @Override - public boolean clearMarker() - throws MojoExecutionException - { + public boolean clearMarker() throws MojoExecutionException { File marker = getMarkerFile(); - File marker2 = getMarkerFile( !this.resolved ); + File marker2 = getMarkerFile(!this.resolved); boolean markResult = marker.delete(); boolean mark2Result = marker2.delete(); return markResult || mark2Result; @@ -189,16 +156,14 @@ public boolean clearMarker() /** * @return Returns the resolved. */ - public boolean isResolved() - { + public boolean isResolved() { return this.resolved; } /** * @param isResolved The resolved to set. */ - public void setResolved( boolean isResolved ) - { + public void setResolved(boolean isResolved) { this.resolved = isResolved; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/UnpackFileMarkerHandler.java b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/UnpackFileMarkerHandler.java index e02f657c7..9dadf452e 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/markers/UnpackFileMarkerHandler.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/markers/UnpackFileMarkerHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.markers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,18 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; +import java.io.File; import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; import org.codehaus.plexus.util.StringUtils; -import java.io.File; - /** * @author Damian Bradicich */ -public class UnpackFileMarkerHandler - extends DefaultFileMarkerHandler -{ +public class UnpackFileMarkerHandler extends DefaultFileMarkerHandler { /** * The ArtifactItem. */ @@ -38,51 +34,44 @@ public class UnpackFileMarkerHandler /** * @param markerFilesDirectory The marker files directory. */ - public UnpackFileMarkerHandler( File markerFilesDirectory ) - { - super( markerFilesDirectory ); + public UnpackFileMarkerHandler(File markerFilesDirectory) { + super(markerFilesDirectory); } /** * @param artifactItem {@link ArtifactItem} * @param markerFilesDirectory the marker files directory. */ - public UnpackFileMarkerHandler( ArtifactItem artifactItem, File markerFilesDirectory ) - { - this( markerFilesDirectory ); - setArtifactItem( artifactItem ); + public UnpackFileMarkerHandler(ArtifactItem artifactItem, File markerFilesDirectory) { + this(markerFilesDirectory); + setArtifactItem(artifactItem); } @Override - protected File getMarkerFile() - { + protected File getMarkerFile() { /** * Build a hash of all include/exclude strings, to determine if an artifactItem has been unpacked using the * include/exclude parameters, this will allow an artifact to be included multiple times with different * include/exclude parameters */ File markerFile; - if ( this.artifactItem == null || ( StringUtils.isEmpty( this.artifactItem.getIncludes() ) - && StringUtils.isEmpty( this.artifactItem.getExcludes() ) ) ) - { + if (this.artifactItem == null + || (StringUtils.isEmpty(this.artifactItem.getIncludes()) + && StringUtils.isEmpty(this.artifactItem.getExcludes()))) { markerFile = super.getMarkerFile(); - } - else - { + } else { int includeExcludeHash = 0; - if ( StringUtils.isNotEmpty( this.artifactItem.getIncludes() ) ) - { + if (StringUtils.isNotEmpty(this.artifactItem.getIncludes())) { includeExcludeHash += this.artifactItem.getIncludes().hashCode(); } - if ( StringUtils.isNotEmpty( this.artifactItem.getExcludes() ) ) - { + if (StringUtils.isNotEmpty(this.artifactItem.getExcludes())) { includeExcludeHash += this.artifactItem.getExcludes().hashCode(); } markerFile = - new File( this.markerFilesDirectory, this.artifact.getId().replace( ':', '-' ) + includeExcludeHash ); + new File(this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + includeExcludeHash); } return markerFile; @@ -91,21 +80,18 @@ protected File getMarkerFile() /** * @param artifactItem {@link #artifactItem} */ - public void setArtifactItem( ArtifactItem artifactItem ) - { + public void setArtifactItem(ArtifactItem artifactItem) { this.artifactItem = artifactItem; - if ( this.artifactItem != null ) - { - setArtifact( this.artifactItem.getArtifact() ); + if (this.artifactItem != null) { + setArtifact(this.artifactItem.getArtifact()); } } /** * @return {@link #artifactItem} */ - public ArtifactItem getArtifactItem() - { + public ArtifactItem getArtifactItem() { return this.artifactItem; } } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ArtifactTranslator.java b/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ArtifactTranslator.java index ec9f6d5f6..aeefae1e9 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ArtifactTranslator.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ArtifactTranslator.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.translators; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,18 +7,18 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.translators; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.logging.Log; import org.apache.maven.shared.transfer.artifact.ArtifactCoordinate; @@ -28,12 +26,11 @@ /** * @author Brian Fox */ -public interface ArtifactTranslator -{ +public interface ArtifactTranslator { /** * @param artifacts set of {@link Artifact}s. * @param log {@link Log} * @return {@link ArtifactCoordinate} */ - Set translate( Set artifacts, Log log ); + Set translate(Set artifacts, Log log); } diff --git a/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ClassifierTypeTranslator.java b/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ClassifierTypeTranslator.java index 9f4759fa7..d9cf3caff 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ClassifierTypeTranslator.java +++ b/src/main/java/org/apache/maven/plugins/dependency/utils/translators/ClassifierTypeTranslator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils.translators; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils.translators; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; @@ -33,9 +31,7 @@ /** * @author Brian Fox */ -public class ClassifierTypeTranslator - implements ArtifactTranslator -{ +public class ClassifierTypeTranslator implements ArtifactTranslator { private final ArtifactHandlerManager artifactHandlerManager; private String classifier; @@ -47,9 +43,8 @@ public class ClassifierTypeTranslator * @param theClassifier The classifier to use. * @param theType The type. */ - public ClassifierTypeTranslator( ArtifactHandlerManager artifactHanderManager, String theClassifier, - String theType ) - { + public ClassifierTypeTranslator( + ArtifactHandlerManager artifactHanderManager, String theClassifier, String theType) { this.artifactHandlerManager = artifactHanderManager; this.classifier = theClassifier; this.type = theType; @@ -61,55 +56,44 @@ public ClassifierTypeTranslator( ArtifactHandlerManager artifactHanderManager, S * org.apache.maven.plugin.logging.Log) */ @Override - public Set translate( Set artifacts, Log log ) - { + public Set translate(Set artifacts, Log log) { Set results; - log.debug( "Translating Artifacts using Classifier: " + this.classifier + " and Type: " + this.type ); + log.debug("Translating Artifacts using Classifier: " + this.classifier + " and Type: " + this.type); results = new LinkedHashSet<>(); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { // this translator must pass both type and classifier here so we // will use the // base artifact value if null comes in final String useType; - if ( StringUtils.isNotEmpty( this.type ) ) - { + if (StringUtils.isNotEmpty(this.type)) { useType = this.type; - } - else - { + } else { useType = artifact.getType(); } - ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler( useType ); + ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler(useType); final String extension; - if ( artifactHandler != null ) - { + if (artifactHandler != null) { extension = artifactHandler.getExtension(); - } - else - { + } else { extension = this.type; } String useClassifier; - if ( StringUtils.isNotEmpty( this.classifier ) ) - { + if (StringUtils.isNotEmpty(this.classifier)) { useClassifier = this.classifier; - } - else - { + } else { useClassifier = artifact.getClassifier(); } DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); - coordinate.setGroupId( artifact.getGroupId() ); - coordinate.setArtifactId( artifact.getArtifactId() ); - coordinate.setVersion( artifact.getVersion() ); - coordinate.setClassifier( useClassifier ); - coordinate.setExtension( extension ); + coordinate.setGroupId(artifact.getGroupId()); + coordinate.setArtifactId(artifact.getArtifactId()); + coordinate.setVersion(artifact.getVersion()); + coordinate.setClassifier(useClassifier); + coordinate.setExtension(extension); // // Create a new artifact // Artifact newArtifact = factory.createArtifactWithClassifier( artifact.getGroupId(), artifact @@ -127,7 +111,7 @@ public Set translate( Set artifacts, Log log ) // newArtifact.setFile( new File( baseDir, path ) ); // } - results.add( coordinate ); + results.add(coordinate); } return results; @@ -136,33 +120,28 @@ public Set translate( Set artifacts, Log log ) /** * @return Returns the type. */ - public String getType() - { + public String getType() { return this.type; } /** * @param theType The type to set. */ - public void setType( String theType ) - { + public void setType(String theType) { this.type = theType; } /** * @return Returns the classifier. */ - public String getClassifier() - { + public String getClassifier() { return this.classifier; } /** * @param theClassifier The classifier to set. */ - public void setClassifier( String theClassifier ) - { + public void setClassifier(String theClassifier) { this.classifier = theClassifier; } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTest.java b/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTest.java index 861ca478c..8fc1e29a6 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,131 +16,119 @@ * specific language governing permissions and limitations * under the License. */ - -import junit.framework.TestCase; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.ProjectBuildingRequest; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; +package org.apache.maven.plugins.dependency; import static org.apache.maven.plugins.dependency.AbstractDependencyMojoTest.ConcreteDependencyMojo.createConcreteDependencyMojoWithArtifactRepositories; import static org.apache.maven.plugins.dependency.AbstractDependencyMojoTest.ConcreteDependencyMojo.createConcreteDependencyMojoWithPluginRepositories; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class AbstractDependencyMojoTest extends TestCase -{ - private MavenSession session = mock( MavenSession.class ); +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import junit.framework.TestCase; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.project.ProjectBuildingRequest; + +public class AbstractDependencyMojoTest extends TestCase { + private MavenSession session = mock(MavenSession.class); - private ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); + private ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); private ArrayList artifactRepos = new ArrayList<>(); private ArrayList pluginRepos = new ArrayList<>(); - static class ConcreteDependencyMojo extends AbstractDependencyMojo - { + static class ConcreteDependencyMojo extends AbstractDependencyMojo { static ConcreteDependencyMojo createConcreteDependencyMojoWithArtifactRepositories( - MavenSession mavenSession, List artifactRepos ) - throws NoSuchFieldException, IllegalAccessException - { + MavenSession mavenSession, List artifactRepos) + throws NoSuchFieldException, IllegalAccessException { ConcreteDependencyMojo cdm = new ConcreteDependencyMojo(); cdm.session = mavenSession; - Field par = AbstractDependencyMojo.class.getDeclaredField( "remoteRepositories" ); - par.setAccessible( true ); - par.set( cdm, artifactRepos ); + Field par = AbstractDependencyMojo.class.getDeclaredField("remoteRepositories"); + par.setAccessible(true); + par.set(cdm, artifactRepos); return cdm; } static ConcreteDependencyMojo createConcreteDependencyMojoWithPluginRepositories( - MavenSession mavenSession, List pluginRepos ) - throws NoSuchFieldException, IllegalAccessException - { + MavenSession mavenSession, List pluginRepos) + throws NoSuchFieldException, IllegalAccessException { ConcreteDependencyMojo cdm = new ConcreteDependencyMojo(); cdm.session = mavenSession; - Field par = AbstractDependencyMojo.class.getDeclaredField( "remotePluginRepositories" ); - par.setAccessible( true ); - par.set( cdm, pluginRepos ); + Field par = AbstractDependencyMojo.class.getDeclaredField("remotePluginRepositories"); + par.setAccessible(true); + par.set(cdm, pluginRepos); return cdm; } @Override - protected void doExecute() - { - } + protected void doExecute() {} } @Override - protected void setUp() throws Exception - { - pluginRepos.add( newRepositoryWithId( "pr-central" ) ); - pluginRepos.add( newRepositoryWithId( "pr-plugins" ) ); + protected void setUp() throws Exception { + pluginRepos.add(newRepositoryWithId("pr-central")); + pluginRepos.add(newRepositoryWithId("pr-plugins")); - artifactRepos.add( newRepositoryWithId( "ar-central" ) ); - artifactRepos.add( newRepositoryWithId( "ar-snapshots" ) ); - artifactRepos.add( newRepositoryWithId( "ar-staging" ) ); + artifactRepos.add(newRepositoryWithId("ar-central")); + artifactRepos.add(newRepositoryWithId("ar-snapshots")); + artifactRepos.add(newRepositoryWithId("ar-staging")); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); } - private static ArtifactRepository newRepositoryWithId( String id ) - { - ArtifactRepository repo = mock( ArtifactRepository.class ); - when( repo.getId() ).thenReturn( id ); + private static ArtifactRepository newRepositoryWithId(String id) { + ArtifactRepository repo = mock(ArtifactRepository.class); + when(repo.getId()).thenReturn(id); return repo; } public void testNewResolveArtifactProjectBuildingRequestRemoteRepositoriesSize() - throws NoSuchFieldException, IllegalAccessException - { - AbstractDependencyMojo mojo = createConcreteDependencyMojoWithArtifactRepositories( session, artifactRepos ); + throws NoSuchFieldException, IllegalAccessException { + AbstractDependencyMojo mojo = createConcreteDependencyMojoWithArtifactRepositories(session, artifactRepos); ProjectBuildingRequest pbr = mojo.newResolveArtifactProjectBuildingRequest(); List rrepos = pbr.getRemoteRepositories(); - assertEquals( 3, rrepos.size() ); + assertEquals(3, rrepos.size()); } public void testNewResolveArtifactProjectBuildingRequestRemoteRepositoriesContents() - throws NoSuchFieldException, IllegalAccessException - { - AbstractDependencyMojo mojo = createConcreteDependencyMojoWithArtifactRepositories( session, artifactRepos ); + throws NoSuchFieldException, IllegalAccessException { + AbstractDependencyMojo mojo = createConcreteDependencyMojoWithArtifactRepositories(session, artifactRepos); ProjectBuildingRequest pbr = mojo.newResolveArtifactProjectBuildingRequest(); List rrepos = pbr.getRemoteRepositories(); - assertEquals( "ar-central", rrepos.get( 0 ).getId() ); - assertEquals( "ar-snapshots", rrepos.get( 1 ).getId() ); - assertEquals( "ar-staging", rrepos.get( 2 ).getId() ); + assertEquals("ar-central", rrepos.get(0).getId()); + assertEquals("ar-snapshots", rrepos.get(1).getId()); + assertEquals("ar-staging", rrepos.get(2).getId()); } public void testNewResolvePluginProjectBuildingRequestRemoteRepositoriesSize() - throws NoSuchFieldException, IllegalAccessException - { - AbstractDependencyMojo mojo = createConcreteDependencyMojoWithPluginRepositories( session, pluginRepos ); + throws NoSuchFieldException, IllegalAccessException { + AbstractDependencyMojo mojo = createConcreteDependencyMojoWithPluginRepositories(session, pluginRepos); ProjectBuildingRequest pbr = mojo.newResolvePluginProjectBuildingRequest(); List rrepos = pbr.getRemoteRepositories(); - assertEquals( 2, rrepos.size() ); + assertEquals(2, rrepos.size()); } public void testNewResolvePluginProjectBuildingRequestRemoteRepositoriesContents() - throws NoSuchFieldException, IllegalAccessException - { - AbstractDependencyMojo mojo = createConcreteDependencyMojoWithPluginRepositories( session, pluginRepos ); + throws NoSuchFieldException, IllegalAccessException { + AbstractDependencyMojo mojo = createConcreteDependencyMojoWithPluginRepositories(session, pluginRepos); ProjectBuildingRequest pbr = mojo.newResolvePluginProjectBuildingRequest(); List rrepos = pbr.getRemoteRepositories(); - assertEquals( "pr-central", rrepos.get( 0 ).getId() ); - assertEquals( "pr-plugins", rrepos.get( 1 ).getId() ); + assertEquals("pr-central", rrepos.get(0).getId()); + assertEquals("pr-plugins", rrepos.get(1).getId()); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTestCase.java b/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTestCase.java index c985594db..89ef23129 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTestCase.java +++ b/src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,81 +16,66 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.io.File; import java.io.IOException; - import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.LegacySupport; import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.LocalRepositoryManager; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -public abstract class AbstractDependencyMojoTestCase - extends AbstractMojoTestCase -{ +public abstract class AbstractDependencyMojoTestCase extends AbstractMojoTestCase { protected File testDir; protected DependencyArtifactStubFactory stubFactory; - protected void setUp( String testDirStr, boolean createFiles ) - throws Exception - { - setUp( testDirStr, createFiles, true ); + protected void setUp(String testDirStr, boolean createFiles) throws Exception { + setUp(testDirStr, createFiles, true); } - protected void setUp( String testDirStr, boolean createFiles, boolean flattenedPath ) - throws Exception - { + protected void setUp(String testDirStr, boolean createFiles, boolean flattenedPath) throws Exception { // required for mojo lookups to work super.setUp(); - testDir = new File( getBasedir(), "target" + File.separatorChar + "unit-tests" + File.separatorChar + testDirStr - + File.separatorChar ); - FileUtils.deleteDirectory( testDir ); - assertFalse( testDir.exists() ); + testDir = new File( + getBasedir(), + "target" + File.separatorChar + "unit-tests" + File.separatorChar + testDirStr + File.separatorChar); + FileUtils.deleteDirectory(testDir); + assertFalse(testDir.exists()); - stubFactory = new DependencyArtifactStubFactory( this.testDir, createFiles, flattenedPath ); + stubFactory = new DependencyArtifactStubFactory(this.testDir, createFiles, flattenedPath); } - protected void tearDown() - { - if ( testDir != null ) - { - try - { - FileUtils.deleteDirectory( testDir ); - } - catch ( IOException e ) - { + protected void tearDown() { + if (testDir != null) { + try { + FileUtils.deleteDirectory(testDir); + } catch (IOException e) { e.printStackTrace(); - fail( "Trying to remove directory:" + testDir + System.lineSeparator() + e.toString() ); + fail("Trying to remove directory:" + testDir + System.lineSeparator() + e.toString()); } - assertFalse( testDir.exists() ); + assertFalse(testDir.exists()); } } - protected void copyFile( AbstractDependencyMojo mojo, File artifact, File destFile ) - throws MojoExecutionException - { - mojo.copyFile( artifact, destFile ); + protected void copyFile(AbstractDependencyMojo mojo, File artifact, File destFile) throws MojoExecutionException { + mojo.copyFile(artifact, destFile); } - - protected void installLocalRepository( LegacySupport legacySupport ) - throws ComponentLookupException - { + protected void installLocalRepository(LegacySupport legacySupport) throws ComponentLookupException { DefaultRepositorySystemSession repoSession = - (DefaultRepositorySystemSession) legacySupport.getRepositorySession(); - RepositorySystem system = lookup( RepositorySystem.class ); + (DefaultRepositorySystemSession) legacySupport.getRepositorySession(); + RepositorySystem system = lookup(RepositorySystem.class); String directory = stubFactory.getWorkingDir().toString(); - LocalRepository localRepository = new LocalRepository( directory ); - LocalRepositoryManager manager = system.newLocalRepositoryManager( repoSession, localRepository ); - repoSession.setLocalRepositoryManager( manager ); + LocalRepository localRepository = new LocalRepository(directory); + LocalRepositoryManager manager = system.newLocalRepositoryManager(repoSession, localRepository); + repoSession.setLocalRepositoryManager(manager); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/TestCollectMojo.java b/src/test/java/org/apache/maven/plugins/dependency/TestCollectMojo.java index cb2715cae..8c3045a83 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/TestCollectMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/TestCollectMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,54 +16,48 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; +import java.io.File; +import java.util.Set; import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.testing.SilentLog; import org.apache.maven.plugins.dependency.resolvers.CollectDependenciesMojo; import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; -import org.apache.maven.plugin.testing.SilentLog; import org.apache.maven.project.MavenProject; -import java.io.File; -import java.util.Set; - -public class TestCollectMojo - extends AbstractDependencyMojoTestCase -{ +public class TestCollectMojo extends AbstractDependencyMojoTestCase { - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "markers", false ); + super.setUp("markers", false); } /** * tests the proper discovery and configuration of the mojo - * + * * @throws Exception if a problem occurs */ - public void testCollectTestEnvironment() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/collect-test/plugin-config.xml" ); - CollectDependenciesMojo mojo = (CollectDependenciesMojo) lookupMojo( "collect", testPom ); - - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + public void testCollectTestEnvironment() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/collect-test/plugin-config.xml"); + CollectDependenciesMojo mojo = (CollectDependenciesMojo) lookupMojo("collect", testPom); + + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - mojo.setSilent( true ); + mojo.setSilent(true); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); mojo.execute(); DependencyStatusSets results = mojo.getResults(); - assertNotNull( results ); - assertEquals( artifacts.size(), results.getResolvedDependencies().size() ); + assertNotNull(results); + assertEquals(artifacts.size(), results.getResolvedDependencies().size()); } /** @@ -73,39 +65,35 @@ public void testCollectTestEnvironment() * * @throws Exception if a problem occurs */ - public void testCollectTestEnvironment_excludeTransitive() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/collect-test/plugin-config.xml" ); - CollectDependenciesMojo mojo = (CollectDependenciesMojo) lookupMojo( "collect", testPom ); - - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + public void testCollectTestEnvironment_excludeTransitive() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/collect-test/plugin-config.xml"); + CollectDependenciesMojo mojo = (CollectDependenciesMojo) lookupMojo("collect", testPom); + + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - mojo.setSilent( true ); + mojo.setSilent(true); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); - setVariableValueToObject( mojo, "excludeTransitive", Boolean.TRUE ); + setVariableValueToObject(mojo, "excludeTransitive", Boolean.TRUE); mojo.execute(); DependencyStatusSets results = mojo.getResults(); - assertNotNull( results ); - assertEquals( directArtifacts.size(), results.getResolvedDependencies().size() ); + assertNotNull(results); + assertEquals(directArtifacts.size(), results.getResolvedDependencies().size()); } - public void testSilent() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/collect-test/plugin-config.xml" ); - CollectDependenciesMojo mojo = (CollectDependenciesMojo) lookupMojo( "collect", testPom ); - mojo.setSilent( false ); + public void testSilent() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/collect-test/plugin-config.xml"); + CollectDependenciesMojo mojo = (CollectDependenciesMojo) lookupMojo("collect", testPom); + mojo.setSilent(false); - assertFalse( mojo.getLog() instanceof SilentLog ); + assertFalse(mojo.getLog() instanceof SilentLog); } // TODO: Test skipping artifacts. } diff --git a/src/test/java/org/apache/maven/plugins/dependency/TestGetMojo.java b/src/test/java/org/apache/maven/plugins/dependency/TestGetMojo.java index fc052e756..4996b6974 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/TestGetMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/TestGetMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.io.File; import java.net.InetAddress; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; @@ -44,73 +42,67 @@ import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.util.security.Constraint; -public class TestGetMojo - extends AbstractDependencyMojoTestCase -{ +public class TestGetMojo extends AbstractDependencyMojoTestCase { private GetMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "markers", false ); + super.setUp("markers", false); - File testPom = new File( getBasedir(), "target/test-classes/unit/get-test/plugin-config.xml" ); - mojo = (GetMojo) lookupMojo( "get", testPom ); + File testPom = new File(getBasedir(), "target/test-classes/unit/get-test/plugin-config.xml"); + mojo = (GetMojo) lookupMojo("get", testPom); - assertNotNull( mojo ); + assertNotNull(mojo); - LegacySupport legacySupport = lookup( LegacySupport.class ); - MavenSession mavenSession = newMavenSession( new MavenProjectStub() ); + LegacySupport legacySupport = lookup(LegacySupport.class); + MavenSession mavenSession = newMavenSession(new MavenProjectStub()); Settings settings = mavenSession.getSettings(); Server server = new Server(); - server.setId( "myserver" ); - server.setUsername( "foo" ); - server.setPassword( "bar" ); - settings.addServer( server ); - legacySupport.setSession( mavenSession ); - - installLocalRepository( legacySupport ); - - setVariableValueToObject( mojo, "session", legacySupport.getSession() ); + server.setId("myserver"); + server.setUsername("foo"); + server.setPassword("bar"); + settings.addServer(server); + legacySupport.setSession(mavenSession); + + installLocalRepository(legacySupport); + + setVariableValueToObject(mojo, "session", legacySupport.getSession()); } /** * Test transitive parameter - * + * * @throws Exception in case of errors */ - public void testTransitive() - throws Exception - { + public void testTransitive() throws Exception { // Set properties, transitive = default value = true - setVariableValueToObject( mojo, "transitive", Boolean.FALSE ); - setVariableValueToObject( mojo, "remoteRepositories", - "central::default::https://repo.maven.apache.org/maven2" ); - mojo.setGroupId( "org.apache.maven" ); - mojo.setArtifactId( "maven-model" ); - mojo.setVersion( "2.0.9" ); + setVariableValueToObject(mojo, "transitive", Boolean.FALSE); + setVariableValueToObject(mojo, "remoteRepositories", "central::default::https://repo.maven.apache.org/maven2"); + mojo.setGroupId("org.apache.maven"); + mojo.setArtifactId("maven-model"); + mojo.setVersion("2.0.9"); mojo.execute(); // Set properties, transitive = false - setVariableValueToObject( mojo, "transitive", Boolean.FALSE ); + setVariableValueToObject(mojo, "transitive", Boolean.FALSE); mojo.execute(); } /** * Test remote repositories parameter - * + * * @throws Exception in case of errors */ - public void testRemoteRepositories() - throws Exception - { - setVariableValueToObject( mojo, "remoteRepositories", "central::default::https://repo.maven.apache.org/maven2," - + "central::::https://repo.maven.apache.org/maven2," + "https://repo.maven.apache.org/maven2" ); - mojo.setGroupId( "org.apache.maven" ); - mojo.setArtifactId( "maven-model" ); - mojo.setVersion( "2.0.9" ); + public void testRemoteRepositories() throws Exception { + setVariableValueToObject( + mojo, + "remoteRepositories", + "central::default::https://repo.maven.apache.org/maven2," + + "central::::https://repo.maven.apache.org/maven2," + "https://repo.maven.apache.org/maven2"); + mojo.setGroupId("org.apache.maven"); + mojo.setArtifactId("maven-model"); + mojo.setVersion("2.0.9"); mojo.execute(); } @@ -120,126 +112,112 @@ public void testRemoteRepositories() * * @throws Exception in case of errors */ - public void testRemoteRepositoriesAuthentication() - throws Exception - { + public void testRemoteRepositoriesAuthentication() throws Exception { org.eclipse.jetty.server.Server server = createServer(); try { server.start(); - ServerConnector serverConnector = (ServerConnector)server.getConnectors()[0]; - String url = "http://" + (serverConnector.getHost() == null ? - InetAddress.getLoopbackAddress().getHostName() : serverConnector.getHost()); + ServerConnector serverConnector = (ServerConnector) server.getConnectors()[0]; + String url = "http://" + + (serverConnector.getHost() == null + ? InetAddress.getLoopbackAddress().getHostName() + : serverConnector.getHost()); url = url + ":" + serverConnector.getLocalPort() + "/maven"; - setVariableValueToObject( mojo, "remoteRepositories", "myserver::default::" + url ); - mojo.setGroupId( "test" ); - mojo.setArtifactId( "test" ); - mojo.setVersion( "1.0" ); + setVariableValueToObject(mojo, "remoteRepositories", "myserver::default::" + url); + mojo.setGroupId("test"); + mojo.setArtifactId("test"); + mojo.setVersion("1.0"); mojo.execute(); - } - finally - { + } finally { server.stop(); } } /** * Test parsing of the remote repositories parameter - * + * * @throws Exception in case of errors */ - public void testParseRepository() - throws Exception - { + public void testParseRepository() throws Exception { ArtifactRepositoryPolicy policy = null; - ArtifactRepository repo = mojo.parseRepository( "central::default::https://repo.maven.apache.org/maven2", policy ); - assertEquals( "central", repo.getId() ); - assertEquals( DefaultRepositoryLayout.class, repo.getLayout().getClass() ); - assertEquals( "https://repo.maven.apache.org/maven2", repo.getUrl() ); - - try - { - repo = mojo.parseRepository( "central::legacy::https://repo.maven.apache.org/maven2", policy ); - fail( "Exception expected: legacy repository not supported anymore" ); - } - catch ( MojoFailureException e ) - { + ArtifactRepository repo = + mojo.parseRepository("central::default::https://repo.maven.apache.org/maven2", policy); + assertEquals("central", repo.getId()); + assertEquals(DefaultRepositoryLayout.class, repo.getLayout().getClass()); + assertEquals("https://repo.maven.apache.org/maven2", repo.getUrl()); + + try { + repo = mojo.parseRepository("central::legacy::https://repo.maven.apache.org/maven2", policy); + fail("Exception expected: legacy repository not supported anymore"); + } catch (MojoFailureException e) { } - repo = mojo.parseRepository( "central::::https://repo.maven.apache.org/maven2", policy ); - assertEquals( "central", repo.getId() ); - assertEquals( DefaultRepositoryLayout.class, repo.getLayout().getClass() ); - assertEquals( "https://repo.maven.apache.org/maven2", repo.getUrl() ); + repo = mojo.parseRepository("central::::https://repo.maven.apache.org/maven2", policy); + assertEquals("central", repo.getId()); + assertEquals(DefaultRepositoryLayout.class, repo.getLayout().getClass()); + assertEquals("https://repo.maven.apache.org/maven2", repo.getUrl()); - repo = mojo.parseRepository( "https://repo.maven.apache.org/maven2", policy ); - assertEquals( "temp", repo.getId() ); - assertEquals( DefaultRepositoryLayout.class, repo.getLayout().getClass() ); - assertEquals( "https://repo.maven.apache.org/maven2", repo.getUrl() ); + repo = mojo.parseRepository("https://repo.maven.apache.org/maven2", policy); + assertEquals("temp", repo.getId()); + assertEquals(DefaultRepositoryLayout.class, repo.getLayout().getClass()); + assertEquals("https://repo.maven.apache.org/maven2", repo.getUrl()); - try - { - mojo.parseRepository( "::::https://repo.maven.apache.org/maven2", policy ); - fail( "Exception expected" ); - } - catch ( MojoFailureException e ) - { + try { + mojo.parseRepository("::::https://repo.maven.apache.org/maven2", policy); + fail("Exception expected"); + } catch (MojoFailureException e) { // expected } - try - { - mojo.parseRepository( "central::https://repo.maven.apache.org/maven2", policy ); - fail( "Exception expected" ); - } - catch ( MojoFailureException e ) - { + try { + mojo.parseRepository("central::https://repo.maven.apache.org/maven2", policy); + fail("Exception expected"); + } catch (MojoFailureException e) { // expected } } - private ContextHandler createContextHandler() - { + private ContextHandler createContextHandler() { ResourceHandler resourceHandler = new ResourceHandler(); - Path resourceDirectory = Paths.get( "src", "test", "resources", "unit", "get-test", "repository" ); - resourceHandler.setResourceBase( resourceDirectory.toString() ); - resourceHandler.setDirectoriesListed( true ); + Path resourceDirectory = Paths.get("src", "test", "resources", "unit", "get-test", "repository"); + resourceHandler.setResourceBase(resourceDirectory.toString()); + resourceHandler.setDirectoriesListed(true); - ContextHandler contextHandler = new ContextHandler( "/maven" ); - contextHandler.setHandler( resourceHandler ); + ContextHandler contextHandler = new ContextHandler("/maven"); + contextHandler.setHandler(resourceHandler); return contextHandler; } - private org.eclipse.jetty.server.Server createServer() - { - org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server( 0 ); - server.setStopAtShutdown( true ); - - LoginService loginService = new HashLoginService( "myrealm", - "src/test/resources/unit/get-test/realm.properties" ); - server.addBean( loginService ); + private org.eclipse.jetty.server.Server createServer() { + org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(0); + server.setStopAtShutdown(true); + + LoginService loginService = + new HashLoginService("myrealm", "src/test/resources/unit/get-test/realm.properties"); + server.addBean(loginService); ConstraintSecurityHandler security = new ConstraintSecurityHandler(); - server.setHandler( security ); + server.setHandler(security); Constraint constraint = new Constraint(); - constraint.setName( "auth" ); - constraint.setAuthenticate( true ); - constraint.setRoles(new String[]{ "userrole" }); + constraint.setName("auth"); + constraint.setAuthenticate(true); + constraint.setRoles(new String[] {"userrole"}); ConstraintMapping mapping = new ConstraintMapping(); - mapping.setPathSpec( "/*" ); - mapping.setConstraint( constraint ); + mapping.setPathSpec("/*"); + mapping.setConstraint(constraint); - security.setConstraintMappings( Collections.singletonList( mapping ) ); - security.setAuthenticator( new BasicAuthenticator() ); - security.setLoginService( loginService ); + security.setConstraintMappings(Collections.singletonList(mapping)); + security.setAuthenticator(new BasicAuthenticator()); + security.setLoginService(loginService); ContextHandler contextHandler = createContextHandler(); - contextHandler.setServer( server ); + contextHandler.setServer(server); - security.setHandler( contextHandler ); - server.setHandler( security ); + security.setHandler(contextHandler); + server.setHandler(security); return server; } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/TestListClassesMojo.java b/src/test/java/org/apache/maven/plugins/dependency/TestListClassesMojo.java index 7f6be4a4c..88cc4c16f 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/TestListClassesMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/TestListClassesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.LegacySupport; import org.apache.maven.plugin.logging.Log; @@ -29,83 +33,74 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - -public class TestListClassesMojo - extends AbstractDependencyMojoTestCase -{ +public class TestListClassesMojo extends AbstractDependencyMojoTestCase { private ListClassesMojo mojo; - protected void setUp() - throws Exception - { - super.setUp( "markers", false ); - File testPom = new File( getBasedir(), "target/test-classes/unit/get-test/plugin-config.xml" ); + protected void setUp() throws Exception { + super.setUp("markers", false); + File testPom = new File(getBasedir(), "target/test-classes/unit/get-test/plugin-config.xml"); - assertTrue( testPom.exists() ); - mojo = (ListClassesMojo) lookupMojo( "list-classes", testPom ); + assertTrue(testPom.exists()); + mojo = (ListClassesMojo) lookupMojo("list-classes", testPom); - assertNotNull( mojo ); + assertNotNull(mojo); - LegacySupport legacySupport = lookup( LegacySupport.class ); - MavenSession session = newMavenSession( new MavenProjectStub() ); + LegacySupport legacySupport = lookup(LegacySupport.class); + MavenSession session = newMavenSession(new MavenProjectStub()); Settings settings = session.getSettings(); Server server = new Server(); - server.setId( "myserver" ); - server.setUsername( "foo" ); - server.setPassword( "bar" ); - settings.addServer( server ); - legacySupport.setSession( session ); + server.setId("myserver"); + server.setUsername("foo"); + server.setPassword("bar"); + settings.addServer(server); + legacySupport.setSession(session); - installLocalRepository( legacySupport ); + installLocalRepository(legacySupport); - setVariableValueToObject( mojo, "session", legacySupport.getSession() ); + setVariableValueToObject(mojo, "session", legacySupport.getSession()); } - public void testListClassesNotTransitive() - throws Exception - { - Path path = Paths.get( "src/test/resources/unit/list-test/testListClassesNotTransitive.txt" ); - List expectedLogArgs = Files.readAllLines( path ); - ArgumentCaptor infoArgsCaptor = ArgumentCaptor.forClass( String.class ); + public void testListClassesNotTransitive() throws Exception { + Path path = Paths.get("src/test/resources/unit/list-test/testListClassesNotTransitive.txt"); + List expectedLogArgs = Files.readAllLines(path); + ArgumentCaptor infoArgsCaptor = ArgumentCaptor.forClass(String.class); - setVariableValueToObject( mojo, "remoteRepositories", "central::default::https://repo.maven.apache.org/maven2," - + "central::::https://repo.maven.apache.org/maven2," + "https://repo.maven.apache.org/maven2" ); - setVariableValueToObject( mojo, "artifact", "org.apache.commons:commons-lang3:3.6" ); - setVariableValueToObject( mojo, "transitive", Boolean.FALSE ); + setVariableValueToObject( + mojo, + "remoteRepositories", + "central::default::https://repo.maven.apache.org/maven2," + + "central::::https://repo.maven.apache.org/maven2," + "https://repo.maven.apache.org/maven2"); + setVariableValueToObject(mojo, "artifact", "org.apache.commons:commons-lang3:3.6"); + setVariableValueToObject(mojo, "transitive", Boolean.FALSE); - Log log = Mockito.mock( Log.class ); - mojo.setLog( log ); + Log log = Mockito.mock(Log.class); + mojo.setLog(log); mojo.execute(); - Mockito.verify( log, Mockito.times( expectedLogArgs.size() ) ).info( infoArgsCaptor.capture() ); - Assert.assertEquals( expectedLogArgs, infoArgsCaptor.getAllValues() ); + Mockito.verify(log, Mockito.times(expectedLogArgs.size())).info(infoArgsCaptor.capture()); + Assert.assertEquals(expectedLogArgs, infoArgsCaptor.getAllValues()); } - public void testListClassesTransitive() - throws Exception - { - Path path = Paths.get( "src/test/resources/unit/list-test/testListClassesTransitive.txt" ); - List expectedLogArgs = Files.readAllLines( path ); - ArgumentCaptor infoArgsCaptor = ArgumentCaptor.forClass( String.class ); + public void testListClassesTransitive() throws Exception { + Path path = Paths.get("src/test/resources/unit/list-test/testListClassesTransitive.txt"); + List expectedLogArgs = Files.readAllLines(path); + ArgumentCaptor infoArgsCaptor = ArgumentCaptor.forClass(String.class); - setVariableValueToObject( mojo, "remoteRepositories", "central::default::https://repo.maven.apache.org/maven2," - + "central::::https://repo.maven.apache.org/maven2," + "https://repo.maven.apache.org/maven2" ); - setVariableValueToObject( mojo, "artifact", "org.apache.commons:commons-lang3:3.6" ); - setVariableValueToObject( mojo, "transitive", Boolean.TRUE ); + setVariableValueToObject( + mojo, + "remoteRepositories", + "central::default::https://repo.maven.apache.org/maven2," + + "central::::https://repo.maven.apache.org/maven2," + "https://repo.maven.apache.org/maven2"); + setVariableValueToObject(mojo, "artifact", "org.apache.commons:commons-lang3:3.6"); + setVariableValueToObject(mojo, "transitive", Boolean.TRUE); - Log log = Mockito.mock( Log.class ); - mojo.setLog( log ); + Log log = Mockito.mock(Log.class); + mojo.setLog(log); mojo.execute(); - Mockito.verify( log, Mockito.times( expectedLogArgs.size() ) ).info( infoArgsCaptor.capture() ); - Assert.assertEquals( expectedLogArgs, infoArgsCaptor.getAllValues() ); + Mockito.verify(log, Mockito.times(expectedLogArgs.size())).info(infoArgsCaptor.capture()); + Assert.assertEquals(expectedLogArgs, infoArgsCaptor.getAllValues()); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/TestPropertiesMojo.java b/src/test/java/org/apache/maven/plugins/dependency/TestPropertiesMojo.java index cd9f37a6a..8f7b7af4a 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/TestPropertiesMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/TestPropertiesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,56 +16,46 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; import java.io.File; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; -public class TestPropertiesMojo - extends AbstractDependencyMojoTestCase -{ - protected void setUp() - throws Exception - { +public class TestPropertiesMojo extends AbstractDependencyMojoTestCase { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "markers", true ); + super.setUp("markers", true); } /** * tests the proper discovery and configuration of the mojo - * + * * @throws Exception in case of errors */ - public void testSetProperties() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/properties-test/plugin-config.xml" ); - PropertiesMojo mojo = (PropertiesMojo) lookupMojo( "properties", testPom ); + public void testSetProperties() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/properties-test/plugin-config.xml"); + PropertiesMojo mojo = (PropertiesMojo) lookupMojo("properties", testPom); - assertNotNull( mojo ); - MavenProject project = (MavenProject) getVariableValueFromObject( mojo, "project" ); - assertNotNull( project ); + assertNotNull(mojo); + MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project"); + assertNotNull(project); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); // this.assertNull( project.getProperties().getProperty( "org.apacha ) ) mojo.execute(); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { File artifactFile = artifact.getFile(); - assertNotNull( artifact.getDependencyConflictId() ); - assertTrue( artifactFile.isFile() ); - + assertNotNull(artifact.getDependencyConflictId()); + assertTrue(artifactFile.isFile()); } - } - -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/dependency/TestSkip.java b/src/test/java/org/apache/maven/plugins/dependency/TestSkip.java index b681f0c5d..156ac83f1 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/TestSkip.java +++ b/src/test/java/org/apache/maven/plugins/dependency/TestSkip.java @@ -1,15 +1,3 @@ -package org.apache.maven.plugins.dependency; - -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.logging.Log; -import org.mockito.ArgumentCaptor; - -import java.io.File; - -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -19,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -28,149 +16,112 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency; + +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -public class TestSkip - extends AbstractDependencyMojoTestCase -{ - public void testSkipAnalyze() - throws Exception - { - doTest( "analyze" ); +import java.io.File; +import org.apache.maven.plugin.Mojo; +import org.apache.maven.plugin.logging.Log; +import org.mockito.ArgumentCaptor; + +public class TestSkip extends AbstractDependencyMojoTestCase { + public void testSkipAnalyze() throws Exception { + doTest("analyze"); } - public void testSkipAnalyzeDepMgt() - throws Exception - { - doTest( "analyze-dep-mgt" ); + public void testSkipAnalyzeDepMgt() throws Exception { + doTest("analyze-dep-mgt"); } - public void testSkipAnalyzeOnly() - throws Exception - { - doTest( "analyze-only" ); + public void testSkipAnalyzeOnly() throws Exception { + doTest("analyze-only"); } - public void testSkipAnalyzeReport() - throws Exception - { - doSpecialTest( "analyze-report" ); + public void testSkipAnalyzeReport() throws Exception { + doSpecialTest("analyze-report"); } - public void testSkipAnalyzeDuplicate() - throws Exception - { - doTest( "analyze-duplicate" ); + public void testSkipAnalyzeDuplicate() throws Exception { + doTest("analyze-duplicate"); } - public void testSkipBuildClasspath() - throws Exception - { - doTest( "build-classpath" ); + public void testSkipBuildClasspath() throws Exception { + doTest("build-classpath"); } - public void testSkipCopy() - throws Exception - { - doTest( "copy" ); + public void testSkipCopy() throws Exception { + doTest("copy"); } - public void testSkipCopyDependencies() - throws Exception - { - doTest( "copy-dependencies" ); + public void testSkipCopyDependencies() throws Exception { + doTest("copy-dependencies"); } - public void testSkipGet() - throws Exception - { - doSpecialTest( "get" ); + public void testSkipGet() throws Exception { + doSpecialTest("get"); } - public void testSkipGoOffline() - throws Exception - { - doTest( "go-offline" ); + public void testSkipGoOffline() throws Exception { + doTest("go-offline"); } - public void testSkipList() - throws Exception - { - doTest( "list" ); + public void testSkipList() throws Exception { + doTest("list"); } - public void testSkipProperties() - throws Exception - { - doTest( "properties" ); + public void testSkipProperties() throws Exception { + doTest("properties"); } - public void testSkipPurgeLocalRepository() - throws Exception - { - doSpecialTest( "purge-local-repository" ); + public void testSkipPurgeLocalRepository() throws Exception { + doSpecialTest("purge-local-repository"); } - public void testSkipResolve() - throws Exception - { - doTest( "resolve" ); + public void testSkipResolve() throws Exception { + doTest("resolve"); } - public void testSkipResolvePlugins() - throws Exception - { - doTest( "resolve-plugins" ); + public void testSkipResolvePlugins() throws Exception { + doTest("resolve-plugins"); } - public void testSkipSources() - throws Exception - { - doTest( "sources" ); + public void testSkipSources() throws Exception { + doTest("sources"); } - public void testSkipTree() - throws Exception - { - doTest( "tree" ); + public void testSkipTree() throws Exception { + doTest("tree"); } - public void testSkipUnpack() - throws Exception - { - doTest( "unpack" ); + public void testSkipUnpack() throws Exception { + doTest("unpack"); } - public void testSkipUnpackDependencies() - throws Exception - { - doTest( "unpack-dependencies" ); + public void testSkipUnpackDependencies() throws Exception { + doTest("unpack-dependencies"); } - protected void doTest( String mojoName ) - throws Exception - { - doConfigTest( mojoName, "plugin-config.xml" ); + protected void doTest(String mojoName) throws Exception { + doConfigTest(mojoName, "plugin-config.xml"); } - protected void doSpecialTest( String mojoName ) - throws Exception - { - doConfigTest( mojoName, "plugin-" + mojoName + "-config.xml" ); + protected void doSpecialTest(String mojoName) throws Exception { + doConfigTest(mojoName, "plugin-" + mojoName + "-config.xml"); } - private void doConfigTest( String mojoName, String configFile ) - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/skip-test/" + configFile ); - Mojo mojo = lookupMojo( mojoName, testPom ); - assertNotNull( mojo ); - Log log = mock( Log.class ); - mojo.setLog( log ); + private void doConfigTest(String mojoName, String configFile) throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/skip-test/" + configFile); + Mojo mojo = lookupMojo(mojoName, testPom); + assertNotNull(mojo); + Log log = mock(Log.class); + mojo.setLog(log); mojo.execute(); - ArgumentCaptor captor = ArgumentCaptor.forClass( String.class ); - verify( log, atLeastOnce() ).info( captor.capture() ); - assertTrue( captor.getValue().contains( "Skipping plugin execution" ) ); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); + verify(log, atLeastOnce()).info(captor.capture()); + assertTrue(captor.getValue().contains("Skipping plugin execution")); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDepMgt.java b/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDepMgt.java index d3392a2d7..7d351437e 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDepMgt.java +++ b/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDepMgt.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.analyze; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import static org.junit.Assert.assertNotEquals; @@ -28,7 +27,6 @@ import java.util.List; import java.util.Map; import java.util.Set; - import junit.framework.TestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; @@ -40,9 +38,7 @@ import org.apache.maven.plugins.dependency.testUtils.stubs.DependencyProjectStub; import org.apache.maven.project.MavenProject; -public class TestAnalyzeDepMgt - extends TestCase -{ +public class TestAnalyzeDepMgt extends TestCase { AnalyzeDepMgt mojo; @@ -58,166 +54,153 @@ public class TestAnalyzeDepMgt DependencyManagement depMgtNoExclusions; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { mojo = new AnalyzeDepMgt(); MavenProject project = new DependencyProjectStub(); - stubFactory = new DependencyArtifactStubFactory( new File( "" ), false ); + stubFactory = new DependencyArtifactStubFactory(new File(""), false); Set allArtifacts = stubFactory.getMixedArtifacts(); Set directArtifacts = stubFactory.getClassifiedArtifacts(); exclusionArtifact = stubFactory.getReleaseArtifact(); - directArtifacts.add( exclusionArtifact ); + directArtifacts.add(exclusionArtifact); ex = new Exclusion(); - ex.setArtifactId( exclusionArtifact.getArtifactId() ); - ex.setGroupId( exclusionArtifact.getGroupId() ); + ex.setArtifactId(exclusionArtifact.getArtifactId()); + ex.setGroupId(exclusionArtifact.getGroupId()); exclusion = new Dependency(); - exclusion.setArtifactId( exclusionArtifact.getArtifactId() ); - exclusion.setGroupId( exclusionArtifact.getGroupId() ); - exclusion.setType( exclusionArtifact.getType() ); - exclusion.setClassifier( "" ); - exclusion.setVersion( "3.0" ); + exclusion.setArtifactId(exclusionArtifact.getArtifactId()); + exclusion.setGroupId(exclusionArtifact.getGroupId()); + exclusion.setType(exclusionArtifact.getType()); + exclusion.setClassifier(""); + exclusion.setVersion("3.0"); - exclusion.addExclusion( ex ); + exclusion.addExclusion(ex); List list = new ArrayList<>(); - list.add( exclusion ); + list.add(exclusion); depMgt = new DependencyManagement(); - depMgt.setDependencies( list ); - - project.setArtifacts( allArtifacts ); - project.setDependencyArtifacts( directArtifacts ); + depMgt.setDependencies(list); - mojo.setProject( project ); + project.setArtifacts(allArtifacts); + project.setDependencyArtifacts(directArtifacts); + mojo.setProject(project); } - public void testGetManagementKey() - throws IOException - { + public void testGetManagementKey() throws IOException { Dependency dep = new Dependency(); - dep.setArtifactId( "artifact" ); - dep.setClassifier( "class" ); - dep.setGroupId( "group" ); - dep.setType( "type" ); + dep.setArtifactId("artifact"); + dep.setClassifier("class"); + dep.setGroupId("group"); + dep.setType("type"); // version isn't used in the key, it can be different - dep.setVersion( "1.1" ); + dep.setVersion("1.1"); Artifact artifact = - stubFactory.createArtifact( "group", "artifact", "1.0", Artifact.SCOPE_COMPILE, "type", "class" ); + stubFactory.createArtifact("group", "artifact", "1.0", Artifact.SCOPE_COMPILE, "type", "class"); // basic case ok - assertEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + assertEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); // now change each one and make sure it fails, then set it back and make // sure it's ok before // testing the next one - dep.setType( "t" ); - assertNotEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setType("t"); + assertNotEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setType( "type" ); - assertEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setType("type"); + assertEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setArtifactId( "a" ); - assertNotEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setArtifactId("a"); + assertNotEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setArtifactId( "artifact" ); - assertEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setArtifactId("artifact"); + assertEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setClassifier( "c" ); - assertNotEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setClassifier("c"); + assertNotEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setClassifier( "class" ); - assertEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setClassifier("class"); + assertEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setGroupId( "g" ); - assertNotEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setGroupId("g"); + assertNotEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setGroupId( "group" ); - dep.setClassifier( null ); - artifact = stubFactory.createArtifact( "group", "artifact", "1.0", Artifact.SCOPE_COMPILE, "type", null ); - assertEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setGroupId("group"); + dep.setClassifier(null); + artifact = stubFactory.createArtifact("group", "artifact", "1.0", Artifact.SCOPE_COMPILE, "type", null); + assertEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); - dep.setClassifier( "" ); - artifact = stubFactory.createArtifact( "group", "artifact", "1.0", Artifact.SCOPE_COMPILE, "type", "" ); - assertEquals( dep.getManagementKey(), mojo.getArtifactManagementKey( artifact ) ); + dep.setClassifier(""); + artifact = stubFactory.createArtifact("group", "artifact", "1.0", Artifact.SCOPE_COMPILE, "type", ""); + assertEquals(dep.getManagementKey(), mojo.getArtifactManagementKey(artifact)); } - public void testAddExclusions() - { + public void testAddExclusions() { - assertEquals( 0, mojo.addExclusions( null ).size() ); + assertEquals(0, mojo.addExclusions(null).size()); List list = new ArrayList<>(); - list.add( ex ); - Map map = mojo.addExclusions( list ); + list.add(ex); + Map map = mojo.addExclusions(list); - assertEquals( 1, map.size() ); - assertTrue( map.containsKey( mojo.getExclusionKey( ex ) ) ); - assertSame( ex, map.get( mojo.getExclusionKey( ex ) ) ); + assertEquals(1, map.size()); + assertTrue(map.containsKey(mojo.getExclusionKey(ex))); + assertSame(ex, map.get(mojo.getExclusionKey(ex))); } - public void testGetExclusionErrors() - { + public void testGetExclusionErrors() { List list = new ArrayList<>(); - list.add( ex ); + list.add(ex); // already tested this method so I can trust it. - Map map = mojo.addExclusions( list ); + Map map = mojo.addExclusions(list); - List l = mojo.getExclusionErrors( map, mojo.getProject().getArtifacts() ); + List l = mojo.getExclusionErrors(map, mojo.getProject().getArtifacts()); - assertEquals( 1, l.size() ); + assertEquals(1, l.size()); - assertEquals( mojo.getExclusionKey( ex ), mojo.getExclusionKey( l.get( 0 ) ) ); + assertEquals(mojo.getExclusionKey(ex), mojo.getExclusionKey(l.get(0))); } - public void testGetMismatch() - throws IOException - { + public void testGetMismatch() throws IOException { Map depMgtMap = new HashMap<>(); - depMgtMap.put( exclusion.getManagementKey(), exclusion ); + depMgtMap.put(exclusion.getManagementKey(), exclusion); - Map results = mojo.getMismatch( depMgtMap, mojo.getProject().getArtifacts() ); + Map results = + mojo.getMismatch(depMgtMap, mojo.getProject().getArtifacts()); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); // the release artifact is used to create the exclusion - assertTrue( results.containsKey( stubFactory.getReleaseArtifact() ) ); - assertSame( exclusion, results.get( stubFactory.getReleaseArtifact() ) ); + assertTrue(results.containsKey(stubFactory.getReleaseArtifact())); + assertSame(exclusion, results.get(stubFactory.getReleaseArtifact())); } - public void testMojo() - throws IOException, MojoExecutionException, MojoFailureException - { - mojo.setIgnoreDirect( false ); + public void testMojo() throws IOException, MojoExecutionException, MojoFailureException { + mojo.setIgnoreDirect(false); // test with nothing in depMgt mojo.execute(); DependencyProjectStub project = (DependencyProjectStub) mojo.getProject(); - project.setDependencyManagement( depMgt ); + project.setDependencyManagement(depMgt); // test with exclusion mojo.execute(); - try - { + try { // test with exclusion - mojo.setFailBuild( true ); + mojo.setFailBuild(true); mojo.execute(); - fail( "Expected exception to fail the build." ); - } - catch ( MojoExecutionException e ) - { + fail("Expected exception to fail the build."); + } catch (MojoExecutionException e) { } - mojo.setFailBuild( true ); - mojo.setIgnoreDirect( true ); + mojo.setFailBuild(true); + mojo.setIgnoreDirect(true); mojo.execute(); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDuplicateMojo.java b/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDuplicateMojo.java index 67d2b5940..1c9750f9f 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDuplicateMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/analyze/TestAnalyzeDuplicateMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.analyze; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,154 +7,134 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.analyze; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; - -import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; /** * @author Vincent Siveton * @version $Id$ */ -public class TestAnalyzeDuplicateMojo - extends AbstractDependencyMojoTestCase -{ - public void testDuplicate() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/duplicate-dependencies/plugin-config.xml" ); - AnalyzeDuplicateMojo mojo = (AnalyzeDuplicateMojo) lookupMojo( "analyze-duplicate", testPom ); - assertNotNull( mojo ); +public class TestAnalyzeDuplicateMojo extends AbstractDependencyMojoTestCase { + public void testDuplicate() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/duplicate-dependencies/plugin-config.xml"); + AnalyzeDuplicateMojo mojo = (AnalyzeDuplicateMojo) lookupMojo("analyze-duplicate", testPom); + assertNotNull(mojo); DuplicateLog log = new DuplicateLog(); - mojo.setLog( log ); + mojo.setLog(log); mojo.execute(); - assertTrue( log.getContent().contains( "List of duplicate dependencies defined in in " - + "your pom.xml" ) ); - assertTrue( log.getContent().contains( "junit:junit:jar" ) ); + assertTrue(log.getContent() + .contains("List of duplicate dependencies defined in in " + "your pom.xml")); + assertTrue(log.getContent().contains("junit:junit:jar")); } - public void testDuplicate2() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/duplicate-dependencies/plugin-config2.xml" ); - AnalyzeDuplicateMojo mojo = (AnalyzeDuplicateMojo) lookupMojo( "analyze-duplicate", testPom ); - assertNotNull( mojo ); + public void testDuplicate2() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/duplicate-dependencies/plugin-config2.xml"); + AnalyzeDuplicateMojo mojo = (AnalyzeDuplicateMojo) lookupMojo("analyze-duplicate", testPom); + assertNotNull(mojo); DuplicateLog log = new DuplicateLog(); - mojo.setLog( log ); + mojo.setLog(log); mojo.execute(); - assertTrue( log.getContent().contains( "List of duplicate dependencies defined in in " - + "your pom.xml" ) ); - assertTrue( log.getContent().contains( "junit:junit:jar" ) ); + assertTrue(log.getContent() + .contains("List of duplicate dependencies defined in in " + "your pom.xml")); + assertTrue(log.getContent().contains("junit:junit:jar")); } - class DuplicateLog - implements Log - { + class DuplicateLog implements Log { StringBuilder sb = new StringBuilder(); /** {@inheritDoc} */ - public void debug( CharSequence content ) - { - print( "debug", content ); + public void debug(CharSequence content) { + print("debug", content); } /** {@inheritDoc} */ - public void debug( CharSequence content, Throwable error ) - { - print( "debug", content, error ); + public void debug(CharSequence content, Throwable error) { + print("debug", content, error); } /** {@inheritDoc} */ - public void debug( Throwable error ) - { - print( "debug", error ); + public void debug(Throwable error) { + print("debug", error); } /** {@inheritDoc} */ - public void info( CharSequence content ) - { - print( "info", content ); + public void info(CharSequence content) { + print("info", content); } /** {@inheritDoc} */ - public void info( CharSequence content, Throwable error ) - { - print( "info", content, error ); + public void info(CharSequence content, Throwable error) { + print("info", content, error); } /** {@inheritDoc} */ - public void info( Throwable error ) - { - print( "info", error ); + public void info(Throwable error) { + print("info", error); } /** {@inheritDoc} */ - public void warn( CharSequence content ) - { - print( "warn", content ); + public void warn(CharSequence content) { + print("warn", content); } /** {@inheritDoc} */ - public void warn( CharSequence content, Throwable error ) - { - print( "warn", content, error ); + public void warn(CharSequence content, Throwable error) { + print("warn", content, error); } /** {@inheritDoc} */ - public void warn( Throwable error ) - { - print( "warn", error ); + public void warn(Throwable error) { + print("warn", error); } /** {@inheritDoc} */ - public void error( CharSequence content ) - { - System.err.println( "[error] " + content.toString() ); + public void error(CharSequence content) { + System.err.println("[error] " + content.toString()); } /** {@inheritDoc} */ - public void error( CharSequence content, Throwable error ) - { + public void error(CharSequence content, Throwable error) { StringWriter sWriter = new StringWriter(); - PrintWriter pWriter = new PrintWriter( sWriter ); + PrintWriter pWriter = new PrintWriter(sWriter); - error.printStackTrace( pWriter ); + error.printStackTrace(pWriter); - System.err.println( "[error] " + content.toString() + System.lineSeparator() + System.lineSeparator() + sWriter.toString() ); + System.err.println("[error] " + content.toString() + System.lineSeparator() + System.lineSeparator() + + sWriter.toString()); } /** * @see org.apache.maven.plugin.logging.Log#error(java.lang.Throwable) */ - public void error( Throwable error ) - { + public void error(Throwable error) { StringWriter sWriter = new StringWriter(); - PrintWriter pWriter = new PrintWriter( sWriter ); + PrintWriter pWriter = new PrintWriter(sWriter); - error.printStackTrace( pWriter ); + error.printStackTrace(pWriter); - System.err.println( "[error] " + sWriter.toString() ); + System.err.println("[error] " + sWriter.toString()); } /** * @see org.apache.maven.plugin.logging.Log#isDebugEnabled() */ - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { // TODO: Not sure how best to set these for this implementation... return false; } @@ -164,55 +142,61 @@ public boolean isDebugEnabled() /** * @see org.apache.maven.plugin.logging.Log#isInfoEnabled() */ - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return true; } /** * @see org.apache.maven.plugin.logging.Log#isWarnEnabled() */ - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } /** * @see org.apache.maven.plugin.logging.Log#isErrorEnabled() */ - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return true; } - private void print( String prefix, CharSequence content ) - { - sb.append( "[" ).append( prefix ).append( "] " ).append( content.toString() ).append( System.lineSeparator() ); + private void print(String prefix, CharSequence content) { + sb.append("[") + .append(prefix) + .append("] ") + .append(content.toString()) + .append(System.lineSeparator()); } - private void print( String prefix, Throwable error ) - { + private void print(String prefix, Throwable error) { StringWriter sWriter = new StringWriter(); - PrintWriter pWriter = new PrintWriter( sWriter ); + PrintWriter pWriter = new PrintWriter(sWriter); - error.printStackTrace( pWriter ); + error.printStackTrace(pWriter); - sb.append( "[" ).append( prefix ).append( "] " ).append( sWriter.toString() ).append( System.lineSeparator() ); + sb.append("[") + .append(prefix) + .append("] ") + .append(sWriter.toString()) + .append(System.lineSeparator()); } - private void print( String prefix, CharSequence content, Throwable error ) - { + private void print(String prefix, CharSequence content, Throwable error) { StringWriter sWriter = new StringWriter(); - PrintWriter pWriter = new PrintWriter( sWriter ); + PrintWriter pWriter = new PrintWriter(sWriter); - error.printStackTrace( pWriter ); + error.printStackTrace(pWriter); - sb.append( "[" ).append( prefix ).append( "] " ).append( content.toString() ).append( System.lineSeparator() ).append( System.lineSeparator() ); - sb.append( sWriter.toString() ).append( System.lineSeparator() ); + sb.append("[") + .append(prefix) + .append("] ") + .append(content.toString()) + .append(System.lineSeparator()) + .append(System.lineSeparator()); + sb.append(sWriter.toString()).append(System.lineSeparator()); } - protected String getContent() - { + protected String getContent() { return sb.toString(); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestArtifactItem.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestArtifactItem.java index 3984ac616..34ed4ac85 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestArtifactItem.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestArtifactItem.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,51 +7,43 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; import java.io.IOException; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; -public class TestArtifactItem - extends AbstractDependencyMojoTestCase -{ +public class TestArtifactItem extends AbstractDependencyMojoTestCase { - protected void setUp() - throws Exception - { - setUp( "artifactItems", false ); + protected void setUp() throws Exception { + setUp("artifactItems", false); } - public void testArtifactItemConstructor() - throws IOException - { - Artifact artifact = stubFactory.createArtifact( "g", "a", "1.0", Artifact.SCOPE_COMPILE, "jar", "one" ); + public void testArtifactItemConstructor() throws IOException { + Artifact artifact = stubFactory.createArtifact("g", "a", "1.0", Artifact.SCOPE_COMPILE, "jar", "one"); - ArtifactItem item = new ArtifactItem( artifact ); + ArtifactItem item = new ArtifactItem(artifact); - assertEquals( item.getArtifact(), artifact ); - assertEquals( item.getArtifactId(), artifact.getArtifactId() ); - assertEquals( item.getGroupId(), artifact.getGroupId() ); - assertEquals( item.getVersion(), artifact.getVersion() ); - assertEquals( item.getClassifier(), artifact.getClassifier() ); - assertEquals( item.getType(), artifact.getType() ); + assertEquals(item.getArtifact(), artifact); + assertEquals(item.getArtifactId(), artifact.getArtifactId()); + assertEquals(item.getGroupId(), artifact.getGroupId()); + assertEquals(item.getVersion(), artifact.getVersion()); + assertEquals(item.getClassifier(), artifact.getClassifier()); + assertEquals(item.getType(), artifact.getType()); } - public void testArtifactItemDefaultType() - { + public void testArtifactItemDefaultType() { ArtifactItem item = new ArtifactItem(); // check type default - assertEquals( "jar", item.getType() ); + assertEquals("jar", item.getType()); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java index 52fa4e9c2..1a8eee21d 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,22 +7,22 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; @@ -35,775 +33,687 @@ import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.project.MavenProject; -public class TestCopyMojo - extends AbstractDependencyMojoTestCase -{ +public class TestCopyMojo extends AbstractDependencyMojoTestCase { private CopyMojo mojo; - protected void setUp() - throws Exception - { - super.setUp( "copy", false, false ); - - File testPom = new File( getBasedir(), "target/test-classes/unit/copy-test/plugin-config.xml" ); - mojo = (CopyMojo) lookupMojo( "copy", testPom ); - mojo.setOutputDirectory( new File( this.testDir, "outputDirectory" ) ); - mojo.setSilent( true ); - - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); - - MavenSession session = newMavenSession( mojo.getProject() ); - setVariableValueToObject( mojo, "session", session ); - - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); - } - - private ArtifactItem getSingleArtifactItem( boolean removeVersion, boolean useBaseVersion ) - throws MojoExecutionException - { - List list = - mojo.getProcessedArtifactItems( new ProcessArtifactItemsRequest( removeVersion, false, useBaseVersion, - false ) ); - return list.get( 0 ); - } - - public void testSetArtifactWithoutPackaging() - throws Exception - { - mojo.setArtifact( "a:b:c" ); - ArtifactItem item = mojo.getArtifactItems().get( 0 ); - assertEquals( "a", item.getGroupId() ); - assertEquals( "b", item.getArtifactId() ); - assertEquals( "c", item.getVersion() ); - assertEquals( "jar", item.getType() ); - assertNull( item.getClassifier() ); - } - - public void testSetArtifactWithoutClassifier() - throws Exception - { - mojo.setArtifact( "a:b:c:d" ); - ArtifactItem item = mojo.getArtifactItems().get( 0 ); - assertEquals( "a", item.getGroupId() ); - assertEquals( "b", item.getArtifactId() ); - assertEquals( "c", item.getVersion() ); - assertEquals( "d", item.getType() ); - assertNull( item.getClassifier() ); - } - - public void testSetArtifact() - throws Exception - { - mojo.setArtifact( "a:b:c:d:e" ); - ArtifactItem item = mojo.getArtifactItems().get( 0 ); - assertEquals( "a", item.getGroupId() ); - assertEquals( "b", item.getArtifactId() ); - assertEquals( "c", item.getVersion() ); - assertEquals( "d", item.getType() ); - assertEquals( "e", item.getClassifier() ); - } - - public void testGetArtifactItems() - throws Exception - { + protected void setUp() throws Exception { + super.setUp("copy", false, false); + + File testPom = new File(getBasedir(), "target/test-classes/unit/copy-test/plugin-config.xml"); + mojo = (CopyMojo) lookupMojo("copy", testPom); + mojo.setOutputDirectory(new File(this.testDir, "outputDirectory")); + mojo.setSilent(true); + + assertNotNull(mojo); + assertNotNull(mojo.getProject()); + + MavenSession session = newMavenSession(mojo.getProject()); + setVariableValueToObject(mojo, "session", session); + + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + installLocalRepository(legacySupport); + } + + private ArtifactItem getSingleArtifactItem(boolean removeVersion, boolean useBaseVersion) + throws MojoExecutionException { + List list = mojo.getProcessedArtifactItems( + new ProcessArtifactItemsRequest(removeVersion, false, useBaseVersion, false)); + return list.get(0); + } + + public void testSetArtifactWithoutPackaging() throws Exception { + mojo.setArtifact("a:b:c"); + ArtifactItem item = mojo.getArtifactItems().get(0); + assertEquals("a", item.getGroupId()); + assertEquals("b", item.getArtifactId()); + assertEquals("c", item.getVersion()); + assertEquals("jar", item.getType()); + assertNull(item.getClassifier()); + } + + public void testSetArtifactWithoutClassifier() throws Exception { + mojo.setArtifact("a:b:c:d"); + ArtifactItem item = mojo.getArtifactItems().get(0); + assertEquals("a", item.getGroupId()); + assertEquals("b", item.getArtifactId()); + assertEquals("c", item.getVersion()); + assertEquals("d", item.getType()); + assertNull(item.getClassifier()); + } + + public void testSetArtifact() throws Exception { + mojo.setArtifact("a:b:c:d:e"); + ArtifactItem item = mojo.getArtifactItems().get(0); + assertEquals("a", item.getGroupId()); + assertEquals("b", item.getArtifactId()); + assertEquals("c", item.getVersion()); + assertEquals("d", item.getType()); + assertEquals("e", item.getClassifier()); + } + + public void testGetArtifactItems() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifact" ); - item.setGroupId( "groupId" ); - item.setVersion( "1.0" ); + item.setArtifactId("artifact"); + item.setGroupId("groupId"); + item.setVersion("1.0"); - List list = new ArrayList<>( 1 ); - list.add( createArtifact( item ) ); + List list = new ArrayList<>(1); + list.add(createArtifact(item)); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); - ArtifactItem result = getSingleArtifactItem( false, false ); - assertEquals( mojo.getOutputDirectory(), result.getOutputDirectory() ); + ArtifactItem result = getSingleArtifactItem(false, false); + assertEquals(mojo.getOutputDirectory(), result.getOutputDirectory()); - File output = new File( mojo.getOutputDirectory(), "override" ); - item.setOutputDirectory( output ); - result = getSingleArtifactItem( false, false ); - assertEquals( output, result.getOutputDirectory() ); + File output = new File(mojo.getOutputDirectory(), "override"); + item.setOutputDirectory(output); + result = getSingleArtifactItem(false, false); + assertEquals(output, result.getOutputDirectory()); } - public void assertFilesExist( Collection items, boolean exist ) - { - for ( ArtifactItem item : items ) - { - assertFileExists( item, exist ); + public void assertFilesExist(Collection items, boolean exist) { + for (ArtifactItem item : items) { + assertFileExists(item, exist); } } - public void assertFileExists( ArtifactItem item, boolean exist ) - { - File file = new File( item.getOutputDirectory(), item.getDestFileName() ); - assertEquals( exist, file.exists() ); + public void assertFileExists(ArtifactItem item, boolean exist) { + File file = new File(item.getOutputDirectory(), item.getDestFileName()); + assertEquals(exist, file.exists()); } - public void testMojoDefaults() - { + public void testMojoDefaults() { CopyMojo themojo = new CopyMojo(); - assertFalse( themojo.isStripVersion() ); - assertFalse( themojo.isSkip() ); - assertFalse( themojo.isStripClassifier() ); + assertFalse(themojo.isStripVersion()); + assertFalse(themojo.isSkip()); + assertFalse(themojo.isStripClassifier()); } - public void testCopyFile() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testCopyFile() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testCopyFileWithBaseVersion() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testCopyFileWithBaseVersion() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifact" ); - item.setGroupId( "groupId" ); - item.setVersion( "1.0-20130210.213424-191" ); - list.add( item ); + item.setArtifactId("artifact"); + item.setGroupId("groupId"); + item.setVersion("1.0-20130210.213424-191"); + list.add(item); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); - mojo.setUseBaseVersion( true ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); + mojo.setUseBaseVersion(true); mojo.execute(); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testSkip() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testSkip() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - mojo.setSkip( true ); - mojo.setArtifactItems( list ); + mojo.setSkip(true); + mojo.setArtifactItems(list); mojo.execute(); - for ( ArtifactItem item : list ) - { + for (ArtifactItem item : list) { // these will be null because no processing has occured only when everything is skipped - assertNull( item.getOutputDirectory() ); - assertNull( item.getDestFileName() ); + assertNull(item.getOutputDirectory()); + assertNull(item.getDestFileName()); } - } - public void testCopyFileNoOverwrite() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testCopyFileNoOverwrite() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - for ( ArtifactItem item : list ) - { + for (ArtifactItem item : list) { // make sure that we copy even if false is set - MDEP-80 - item.setOverWrite( "false" ); + item.setOverWrite("false"); } - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testCopyToLocation() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); + public void testCopyToLocation() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); + ArtifactItem item = list.get(0); + item.setOutputDirectory(new File(mojo.getOutputDirectory(), "testOverride")); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testCopyStripVersionSetInMojo() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testCopyStripVersionSetInMojo() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); - mojo.setStripVersion( true ); + ArtifactItem item = list.get(0); + item.setOutputDirectory(new File(mojo.getOutputDirectory(), "testOverride")); + mojo.setStripVersion(true); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertEquals( DependencyUtil.getFormattedFileName( item.getArtifact(), true ), item.getDestFileName() ); + assertEquals(DependencyUtil.getFormattedFileName(item.getArtifact(), true), item.getDestFileName()); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testCopyStripClassifierSetInMojo() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testCopyStripClassifierSetInMojo() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); - mojo.setStripClassifier( true ); + ArtifactItem item = list.get(0); + item.setOutputDirectory(new File(mojo.getOutputDirectory(), "testOverride")); + mojo.setStripClassifier(true); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertEquals( DependencyUtil.getFormattedFileName( item.getArtifact(), false, false, false, true ), - item.getDestFileName() ); + assertEquals( + DependencyUtil.getFormattedFileName(item.getArtifact(), false, false, false, true), + item.getDestFileName()); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testNonClassifierStrip() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getReleaseAndSnapshotArtifacts() ); - mojo.setStripVersion( true ); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + public void testNonClassifierStrip() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getReleaseAndSnapshotArtifacts()); + mojo.setStripVersion(true); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testNonClassifierNoStrip() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getReleaseAndSnapshotArtifacts() ); + public void testNonClassifierNoStrip() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getReleaseAndSnapshotArtifacts()); - mojo.setArtifactItems( createArtifactItemArtifacts( list ) ); + mojo.setArtifactItems(createArtifactItemArtifacts(list)); mojo.execute(); - assertFilesExist( list, true ); + assertFilesExist(list, true); } - public void testMissingVersionNotFound() - throws Exception - { + public void testMissingVersionNotFound() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); - try - { + try { mojo.execute(); - fail( "Expected Exception Here." ); - } - catch ( MojoExecutionException e ) - { + fail("Expected Exception Here."); + } catch (MojoExecutionException e) { // caught the expected exception. } } - public List getDependencyList( ArtifactItem item ) - { + public List getDependencyList(ArtifactItem item) { Dependency dep = new Dependency(); - dep.setArtifactId( item.getArtifactId() ); - dep.setClassifier( item.getClassifier() ); - dep.setGroupId( item.getGroupId() ); - dep.setType( item.getType() ); - dep.setVersion( "2.0-SNAPSHOT" ); + dep.setArtifactId(item.getArtifactId()); + dep.setClassifier(item.getClassifier()); + dep.setGroupId(item.getGroupId()); + dep.setType(item.getType()); + dep.setVersion("2.0-SNAPSHOT"); Dependency dep2 = new Dependency(); - dep2.setArtifactId( item.getArtifactId() ); - dep2.setClassifier( "classifier" ); - dep2.setGroupId( item.getGroupId() ); - dep2.setType( item.getType() ); - dep2.setVersion( "2.1" ); + dep2.setArtifactId(item.getArtifactId()); + dep2.setClassifier("classifier"); + dep2.setGroupId(item.getGroupId()); + dep2.setType(item.getType()); + dep2.setVersion("2.1"); - List list = new ArrayList<>( 2 ); - list.add( dep2 ); - list.add( dep ); + List list = new ArrayList<>(2); + list.add(dep2); + list.add(dep); return list; } - public void testMissingVersionFromDependencies() - throws Exception - { + public void testMissingVersionFromDependencies() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); MavenProject project = mojo.getProject(); - project.setDependencies( createDependencyArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createDependencyArtifacts(getDependencyList(item))); mojo.execute(); - this.assertFileExists( item, true ); - assertEquals( "2.0-SNAPSHOT", item.getVersion() ); + this.assertFileExists(item, true); + assertEquals("2.0-SNAPSHOT", item.getVersion()); } - public void testMissingVersionFromDependenciesLooseMatch() - throws Exception - { + public void testMissingVersionFromDependenciesLooseMatch() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); MavenProject project = mojo.getProject(); - project.setDependencies( createDependencyArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createDependencyArtifacts(getDependencyList(item))); // ensure dependency exists - item.setClassifier( "sources" ); - item.setType( "jar" ); + item.setClassifier("sources"); + item.setType("jar"); // pre-create item - item.setVersion( "2.1" ); - createArtifact( item ); - item.setVersion( null ); + item.setVersion("2.1"); + createArtifact(item); + item.setVersion(null); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); mojo.execute(); - this.assertFileExists( item, true ); - assertEquals( "2.1", item.getVersion() ); + this.assertFileExists(item, true); + assertEquals("2.1", item.getVersion()); } - public void testMissingVersionFromDependenciesWithClassifier() - throws Exception - { + public void testMissingVersionFromDependenciesWithClassifier() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier("classifier"); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); MavenProject project = mojo.getProject(); - project.setDependencies( createDependencyArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createDependencyArtifacts(getDependencyList(item))); mojo.execute(); - this.assertFileExists( item, true ); - assertEquals( "2.1", item.getVersion() ); + this.assertFileExists(item, true); + assertEquals("2.1", item.getVersion()); } - public List getDependencyMgtList( ArtifactItem item ) - { + public List getDependencyMgtList(ArtifactItem item) { Dependency dep = new Dependency(); - dep.setArtifactId( item.getArtifactId() ); - dep.setClassifier( item.getClassifier() ); - dep.setGroupId( item.getGroupId() ); - dep.setType( item.getType() ); - dep.setVersion( "3.0-SNAPSHOT" ); + dep.setArtifactId(item.getArtifactId()); + dep.setClassifier(item.getClassifier()); + dep.setGroupId(item.getGroupId()); + dep.setType(item.getType()); + dep.setVersion("3.0-SNAPSHOT"); Dependency dep2 = new Dependency(); - dep2.setArtifactId( item.getArtifactId() ); - dep2.setClassifier( "classifier" ); - dep2.setGroupId( item.getGroupId() ); - dep2.setType( item.getType() ); - dep2.setVersion( "3.1" ); + dep2.setArtifactId(item.getArtifactId()); + dep2.setClassifier("classifier"); + dep2.setGroupId(item.getGroupId()); + dep2.setType(item.getType()); + dep2.setVersion("3.1"); - List list = new ArrayList<>( 2 ); - list.add( dep2 ); - list.add( dep ); + List list = new ArrayList<>(2); + list.add(dep2); + list.add(dep); return list; } - public void testMissingVersionFromDependencyMgt() - throws Exception - { + public void testMissingVersionFromDependencyMgt() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); MavenProject project = mojo.getProject(); - project.setDependencies( getDependencyList( item ) ); + project.setDependencies(getDependencyList(item)); item = new ArtifactItem(); - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId-2"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); + list.add(item); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - project.getDependencyManagement().setDependencies( createDependencyArtifacts( getDependencyMgtList( item ) ) ); + project.getDependencyManagement().setDependencies(createDependencyArtifacts(getDependencyMgtList(item))); mojo.execute(); - this.assertFileExists( item, true ); - assertEquals( "3.0-SNAPSHOT", item.getVersion() ); + this.assertFileExists(item, true); + assertEquals("3.0-SNAPSHOT", item.getVersion()); } - public void testMissingVersionFromDependencyMgtLooseMatch() - throws Exception - { + public void testMissingVersionFromDependencyMgtLooseMatch() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); MavenProject project = mojo.getProject(); - project.setDependencies( getDependencyList( item ) ); + project.setDependencies(getDependencyList(item)); item = new ArtifactItem(); - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId-2"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); + list.add(item); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - project.getDependencyManagement().setDependencies( createDependencyArtifacts( getDependencyMgtList( item ) ) ); + project.getDependencyManagement().setDependencies(createDependencyArtifacts(getDependencyMgtList(item))); - item.setType( "jar" ); + item.setType("jar"); // pre-create item - item.setVersion( "3.1" ); - createArtifact( item ); - item.setVersion( null ); + item.setVersion("3.1"); + createArtifact(item); + item.setVersion(null); mojo.execute(); - this.assertFileExists( item, true ); - assertEquals( "3.1", item.getVersion() ); + this.assertFileExists(item, true); + assertEquals("3.1", item.getVersion()); } - public void testMissingVersionFromDependencyMgtWithClassifier() - throws Exception - { + public void testMissingVersionFromDependencyMgtWithClassifier() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier("classifier"); + item.setGroupId("groupId"); + item.setType("type"); MavenProject project = mojo.getProject(); - project.setDependencies( getDependencyList( item ) ); + project.setDependencies(getDependencyList(item)); item = new ArtifactItem(); - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId-2"); + item.setClassifier("classifier"); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); + list.add(item); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - project.getDependencyManagement().setDependencies( createDependencyArtifacts( getDependencyMgtList( item ) ) ); + project.getDependencyManagement().setDependencies(createDependencyArtifacts(getDependencyMgtList(item))); mojo.execute(); - this.assertFileExists( item, true ); - assertEquals( "3.1", item.getVersion() ); + this.assertFileExists(item, true); + assertEquals("3.1", item.getVersion()); } - public void testArtifactNotFound() - throws Exception - { - dotestArtifactExceptions( false, true ); + public void testArtifactNotFound() throws Exception { + dotestArtifactExceptions(false, true); } - public void testArtifactResolutionException() - throws Exception - { - dotestArtifactExceptions( true, false ); + public void testArtifactResolutionException() throws Exception { + dotestArtifactExceptions(true, false); } - public void dotestArtifactExceptions( boolean are, boolean anfe ) - throws Exception - { + public void dotestArtifactExceptions(boolean are, boolean anfe) throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); - item.setVersion( "1.0" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); + item.setVersion("1.0"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); - try - { + try { mojo.execute(); - fail( "ExpectedException" ); - } - catch ( MojoExecutionException e ) - { - assertEquals( "Unable to find/resolve artifact.", e.getMessage() ); + fail("ExpectedException"); + } catch (MojoExecutionException e) { + assertEquals("Unable to find/resolve artifact.", e.getMessage()); } } - public void testNoArtifactItems() - { - try - { - mojo.getProcessedArtifactItems( new ProcessArtifactItemsRequest( false, false, false, false ) ); - fail( "Expected Exception" ); - } - catch ( MojoExecutionException e ) - { - assertEquals( "There are no artifactItems configured.", e.getMessage() ); + public void testNoArtifactItems() { + try { + mojo.getProcessedArtifactItems(new ProcessArtifactItemsRequest(false, false, false, false)); + fail("Expected Exception"); + } catch (MojoExecutionException e) { + assertEquals("There are no artifactItems configured.", e.getMessage()); } - } - public void testCopyDontOverWriteReleases() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testCopyDontOverWriteReleases() throws Exception { + stubFactory.setCreateFiles(true); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( release ); + ArtifactItem item = new ArtifactItem(release); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); + mojo.setOverWriteIfNewer(false); mojo.execute(); - File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() ); + File copiedFile = new File(item.getOutputDirectory(), item.getDestFileName()); - Thread.sleep( 100 ); + Thread.sleep(100); // round up to the next second long time = System.currentTimeMillis() + 1000; - time = time - ( time % 1000 ); - copiedFile.setLastModified( time ); - Thread.sleep( 100 ); + time = time - (time % 1000); + copiedFile.setLastModified(time); + Thread.sleep(100); mojo.execute(); - assertEquals( time, copiedFile.lastModified() ); + assertEquals(time, copiedFile.lastModified()); } - public void testCopyDontOverWriteSnapshots() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testCopyDontOverWriteSnapshots() throws Exception { + stubFactory.setCreateFiles(true); Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(artifact.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( artifact ); + ArtifactItem item = new ArtifactItem(artifact); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); + mojo.setOverWriteIfNewer(false); mojo.execute(); - File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() ); + File copiedFile = new File(item.getOutputDirectory(), item.getDestFileName()); - Thread.sleep( 100 ); + Thread.sleep(100); // round up to the next second long time = System.currentTimeMillis() + 1000; - time = time - ( time % 1000 ); - assertTrue( copiedFile.setLastModified( time ) ); - Thread.sleep( 100 ); + time = time - (time % 1000); + assertTrue(copiedFile.setLastModified(time)); + Thread.sleep(100); mojo.execute(); - assertEquals( time, copiedFile.lastModified() ); + assertEquals(time, copiedFile.lastModified()); } - public void testCopyOverWriteReleases() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testCopyOverWriteReleases() throws Exception { + stubFactory.setCreateFiles(true); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( 1000L ) ); - assertEquals( 1000L, release.getFile().lastModified() ); + assertTrue(release.getFile().setLastModified(1000L)); + assertEquals(1000L, release.getFile().lastModified()); - ArtifactItem item = new ArtifactItem( release ); + ArtifactItem item = new ArtifactItem(release); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); - mojo.setOverWriteReleases( true ); + mojo.setOverWriteIfNewer(false); + mojo.setOverWriteReleases(true); mojo.execute(); - File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() ); + File copiedFile = new File(item.getOutputDirectory(), item.getDestFileName()); - assertTrue( copiedFile.setLastModified( 2000L ) ); - assertEquals( 2000L, copiedFile.lastModified() ); + assertTrue(copiedFile.setLastModified(2000L)); + assertEquals(2000L, copiedFile.lastModified()); mojo.execute(); long timeCopyNow = copiedFile.lastModified(); - assertEquals( 1000L, timeCopyNow ); + assertEquals(1000L, timeCopyNow); } - public void testCopyOverWriteSnapshot() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testCopyOverWriteSnapshot() throws Exception { + stubFactory.setCreateFiles(true); Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( 1000L ) ); - assertEquals( 1000L, artifact.getFile().lastModified() ); + assertTrue(artifact.getFile().setLastModified(1000L)); + assertEquals(1000L, artifact.getFile().lastModified()); - ArtifactItem item = new ArtifactItem( artifact ); + ArtifactItem item = new ArtifactItem(artifact); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); - mojo.setOverWriteReleases( false ); - mojo.setOverWriteSnapshots( true ); + mojo.setOverWriteIfNewer(false); + mojo.setOverWriteReleases(false); + mojo.setOverWriteSnapshots(true); mojo.execute(); - File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() ); + File copiedFile = new File(item.getOutputDirectory(), item.getDestFileName()); - assertTrue( copiedFile.setLastModified( 2000L ) ); - assertEquals( 2000L, copiedFile.lastModified() ); + assertTrue(copiedFile.setLastModified(2000L)); + assertEquals(2000L, copiedFile.lastModified()); mojo.execute(); long timeCopyNow = copiedFile.lastModified(); - assertEquals( 1000L, timeCopyNow ); + assertEquals(1000L, timeCopyNow); } - public void testCopyOverWriteIfNewer() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testCopyOverWriteIfNewer() throws Exception { + stubFactory.setCreateFiles(true); Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(artifact.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( artifact ); + ArtifactItem item = new ArtifactItem(artifact); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - mojo.setOverWriteIfNewer( true ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); + mojo.setOverWriteIfNewer(true); mojo.execute(); - File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() ); + File copiedFile = new File(item.getOutputDirectory(), item.getDestFileName()); // set dest to be old long time = System.currentTimeMillis() - 10000; - time = time - ( time % 1000 ); - assertTrue( copiedFile.setLastModified( time ) ); + time = time - (time % 1000); + assertTrue(copiedFile.setLastModified(time)); // set source to be newer - assertTrue( artifact.getFile().setLastModified( time + 4000 ) ); + assertTrue(artifact.getFile().setLastModified(time + 4000)); mojo.execute(); - assertTrue( time < copiedFile.lastModified() ); + assertTrue(time < copiedFile.lastModified()); } - public void testCopyFileWithOverideLocalRepo() - throws Exception - { + public void testCopyFileWithOverideLocalRepo() throws Exception { final File localRepo = stubFactory.getWorkingDir(); - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - File execLocalRepo = new File( this.testDir.getAbsolutePath(), "executionLocalRepo" ); - assertFalse( execLocalRepo.exists() ); + File execLocalRepo = new File(this.testDir.getAbsolutePath(), "executionLocalRepo"); + assertFalse(execLocalRepo.exists()); - stubFactory.setWorkingDir( execLocalRepo ); - createArtifactItemArtifacts( list ); + stubFactory.setWorkingDir(execLocalRepo); + createArtifactItemArtifacts(list); - assertFalse( "default local repo should not exist", localRepo.exists() ); + assertFalse("default local repo should not exist", localRepo.exists()); - mojo.setLocalRepositoryDirectory( execLocalRepo ); + mojo.setLocalRepositoryDirectory(execLocalRepo); mojo.execute(); - assertFilesExist( list, true ); - - } - - private List createDependencyArtifacts( List items ) - throws IOException - { - stubFactory.setCreateFiles( true ); - for ( Dependency item : items ) - { - String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); - stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), - VersionRange.createFromVersion( item.getVersion() ), null, item.getType(), - classifier, item.isOptional() ); + assertFilesExist(list, true); + } + + private List createDependencyArtifacts(List items) throws IOException { + stubFactory.setCreateFiles(true); + for (Dependency item : items) { + String classifier = "".equals(item.getClassifier()) ? null : item.getClassifier(); + stubFactory.createArtifact( + item.getGroupId(), + item.getArtifactId(), + VersionRange.createFromVersion(item.getVersion()), + null, + item.getType(), + classifier, + item.isOptional()); } return items; } - private List createArtifactItemArtifacts( List items ) - throws IOException - { - for ( ArtifactItem item : items ) - { - createArtifact( item ); + private List createArtifactItemArtifacts(List items) throws IOException { + for (ArtifactItem item : items) { + createArtifact(item); } return items; } - private ArtifactItem createArtifact( ArtifactItem item ) - throws IOException - { - stubFactory.setCreateFiles( true ); + private ArtifactItem createArtifact(ArtifactItem item) throws IOException { + stubFactory.setCreateFiles(true); - String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); + String classifier = "".equals(item.getClassifier()) ? null : item.getClassifier(); String version = item.getVersion() != null ? item.getVersion() : item.getBaseVersion(); - stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), version, null, item.getType(), - classifier ); + stubFactory.createArtifact(item.getGroupId(), item.getArtifactId(), version, null, item.getType(), classifier); return item; } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestIncludeExcludeUnpackMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestIncludeExcludeUnpackMojo.java index 9134d062c..335b76be7 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestIncludeExcludeUnpackMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestIncludeExcludeUnpackMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,21 +7,21 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.LegacySupport; @@ -32,9 +30,7 @@ import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.codehaus.plexus.archiver.manager.ArchiverManager; -public class TestIncludeExcludeUnpackMojo - extends AbstractDependencyMojoTestCase -{ +public class TestIncludeExcludeUnpackMojo extends AbstractDependencyMojoTestCase { private final String PACKED_FILE = "test.zip"; private final String UNPACKED_FILE_PREFIX = "test"; @@ -45,75 +41,65 @@ public class TestIncludeExcludeUnpackMojo private UnpackMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "unpack", true, false ); + super.setUp("unpack", true, false); - File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-test/plugin-config.xml" ); - mojo = (UnpackMojo) lookupMojo( "unpack", testPom ); - mojo.setOutputDirectory( new File( this.testDir, "outputDirectory" ) ); + File testPom = new File(getBasedir(), "target/test-classes/unit/unpack-test/plugin-config.xml"); + mojo = (UnpackMojo) lookupMojo("unpack", testPom); + mojo.setOutputDirectory(new File(this.testDir, "outputDirectory")); // mojo.silent = true; // it needs to get the archivermanager // stubFactory.setUnpackableFile( mojo.getArchiverManager() ); // i'm using one file repeatedly to archive so I can test the name // programmatically. - stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar + PACKED_FILE_PATH ) ); - Artifact artifact = stubFactory.createArtifact( "test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null ); - ArtifactItem item = stubFactory.getArtifactItem( artifact ); - List list = new ArrayList<>( 1 ); - list.add( item ); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + stubFactory.setSrcFile(new File(getBasedir() + File.separatorChar + PACKED_FILE_PATH)); + Artifact artifact = stubFactory.createArtifact("test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null); + ArtifactItem item = stubFactory.getArtifactItem(artifact); + List list = new ArrayList<>(1); + list.add(item); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); - mojo.setArchiverManager( lookup( ArchiverManager.class ) ); + mojo.setArchiverManager(lookup(ArchiverManager.class)); - mojo.setMarkersDirectory( new File( this.testDir, "markers" ) ); - mojo.setArtifactItems( list ); + mojo.setMarkersDirectory(new File(this.testDir, "markers")); + mojo.setArtifactItems(list); - MavenSession session = newMavenSession( mojo.getProject() ); - setVariableValueToObject( mojo, "session", session ); + MavenSession session = newMavenSession(mojo.getProject()); + setVariableValueToObject(mojo, "session", session); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + installLocalRepository(legacySupport); } - protected void tearDown() - { + protected void tearDown() { super.tearDown(); mojo = null; System.gc(); } - public void assertMarkerFiles( Collection items, boolean exist ) - { - for ( ArtifactItem item : items ) - { - assertMarkerFile( exist, item ); + public void assertMarkerFiles(Collection items, boolean exist) { + for (ArtifactItem item : items) { + assertMarkerFile(exist, item); } } - public void assertMarkerFile( boolean val, ArtifactItem item ) - { - UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler( item, mojo.getMarkersDirectory() ); - try - { - assertEquals( val, handle.isMarkerSet() ); - } - catch ( MojoExecutionException e ) - { - fail( e.getLongMessage() ); + public void assertMarkerFile(boolean val, ArtifactItem item) { + UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler(item, mojo.getMarkersDirectory()); + try { + assertEquals(val, handle.isMarkerSet()); + } catch (MojoExecutionException e) { + fail(e.getLongMessage()); } } - private void assertUnpacked( boolean unpacked, String fileName ) - { - File destFile = new File( mojo.getOutputDirectory().getAbsolutePath(), fileName ); - assertEquals( unpacked, destFile.exists() ); + private void assertUnpacked(boolean unpacked, String fileName) { + File destFile = new File(mojo.getOutputDirectory().getAbsolutePath(), fileName); + assertEquals(unpacked, destFile.exists()); } /** @@ -121,15 +107,13 @@ private void assertUnpacked( boolean unpacked, String fileName ) * * @throws Exception in case of errors. */ - public void testUnpackIncludesManyFiles() - throws Exception - { - mojo.setIncludes( "**/*1" + UNPACKED_FILE_SUFFIX ); + public void testUnpackIncludesManyFiles() throws Exception { + mojo.setIncludes("**/*1" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** @@ -137,15 +121,13 @@ public void testUnpackIncludesManyFiles() * * @throws Exception in case of errors. */ - public void testUnpackIncludesSingleFile() - throws Exception - { - mojo.setIncludes( "**/test2" + UNPACKED_FILE_SUFFIX ); + public void testUnpackIncludesSingleFile() throws Exception { + mojo.setIncludes("**/test2" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** @@ -153,15 +135,13 @@ public void testUnpackIncludesSingleFile() * * @throws Exception in case of errors. */ - public void testUnpackIncludesAllFiles() - throws Exception - { - mojo.setIncludes( "**/*" ); + public void testUnpackIncludesAllFiles() throws Exception { + mojo.setIncludes("**/*"); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** @@ -169,15 +149,13 @@ public void testUnpackIncludesAllFiles() * * @throws Exception in case of errors. */ - public void testUnpackExcludesManyFiles() - throws Exception - { - mojo.setExcludes( "**/*1" + UNPACKED_FILE_SUFFIX ); + public void testUnpackExcludesManyFiles() throws Exception { + mojo.setExcludes("**/*1" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** @@ -185,15 +163,13 @@ public void testUnpackExcludesManyFiles() * * @throws Exception in case of errors. */ - public void testUnpackExcludesSingleFile() - throws Exception - { - mojo.setExcludes( "**/test2" + UNPACKED_FILE_SUFFIX ); + public void testUnpackExcludesSingleFile() throws Exception { + mojo.setExcludes("**/test2" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** @@ -201,118 +177,106 @@ public void testUnpackExcludesSingleFile() * * @throws Exception in case of errors. */ - public void testUnpackExcludesAllFiles() - throws Exception - { - mojo.setExcludes( "**/*" ); + public void testUnpackExcludesAllFiles() throws Exception { + mojo.setExcludes("**/*"); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } - public void testNoIncludeExcludes() - throws Exception - { + public void testNoIncludeExcludes() throws Exception { mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } - public void testIncludeArtifactItemOverride() - throws Exception - { - Artifact artifact = stubFactory.createArtifact( "test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null ); - ArtifactItem item = stubFactory.getArtifactItem( artifact ); - item.setIncludes( "**/*" ); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - mojo.setIncludes( "**/test2" + UNPACKED_FILE_SUFFIX ); + public void testIncludeArtifactItemOverride() throws Exception { + Artifact artifact = stubFactory.createArtifact("test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null); + ArtifactItem item = stubFactory.getArtifactItem(artifact); + item.setIncludes("**/*"); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); + mojo.setIncludes("**/test2" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } - public void testExcludeArtifactItemOverride() - throws Exception - { - Artifact artifact = stubFactory.createArtifact( "test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null ); - ArtifactItem item = stubFactory.getArtifactItem( artifact ); - item.setExcludes( "**/*" ); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - mojo.setExcludes( "**/test2" + UNPACKED_FILE_SUFFIX ); + public void testExcludeArtifactItemOverride() throws Exception { + Artifact artifact = stubFactory.createArtifact("test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null); + ArtifactItem item = stubFactory.getArtifactItem(artifact); + item.setExcludes("**/*"); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); + mojo.setExcludes("**/test2" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } - public void testIncludeArtifactItemMultipleMarker() - throws Exception - { + public void testIncludeArtifactItemMultipleMarker() throws Exception { List list = new ArrayList<>(); - Artifact artifact = stubFactory.createArtifact( "test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null ); - ArtifactItem item = stubFactory.getArtifactItem( artifact ); - item.setOverWrite( "false" ); - item.setIncludes( "**/test2" + UNPACKED_FILE_SUFFIX ); - list.add( item ); - item = stubFactory.getArtifactItem( artifact ); - item.setOverWrite( "false" ); - item.setIncludes( "**/test3" + UNPACKED_FILE_SUFFIX ); - list.add( item ); - mojo.setArtifactItems( list ); + Artifact artifact = stubFactory.createArtifact("test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null); + ArtifactItem item = stubFactory.getArtifactItem(artifact); + item.setOverWrite("false"); + item.setIncludes("**/test2" + UNPACKED_FILE_SUFFIX); + list.add(item); + item = stubFactory.getArtifactItem(artifact); + item.setOverWrite("false"); + item.setIncludes("**/test3" + UNPACKED_FILE_SUFFIX); + list.add(item); + mojo.setArtifactItems(list); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); - assertMarkerFiles( mojo.getArtifactItems(), true ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); + assertMarkerFiles(mojo.getArtifactItems(), true); } - public void testIncludeArtifactItemMultipleExecutions() - throws Exception - { + public void testIncludeArtifactItemMultipleExecutions() throws Exception { List list = new ArrayList<>(); - Artifact artifact = stubFactory.createArtifact( "test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null ); - ArtifactItem item = stubFactory.getArtifactItem( artifact ); - item.setOverWrite( "false" ); - item.setIncludes( "**/test2" + UNPACKED_FILE_SUFFIX ); - list.add( item ); - item = stubFactory.getArtifactItem( artifact ); - item.setOverWrite( "false" ); - item.setIncludes( "**/test3" + UNPACKED_FILE_SUFFIX ); - list.add( item ); - mojo.setArtifactItems( list ); + Artifact artifact = stubFactory.createArtifact("test", "test", "1.0", Artifact.SCOPE_COMPILE, "jar", null); + ArtifactItem item = stubFactory.getArtifactItem(artifact); + item.setOverWrite("false"); + item.setIncludes("**/test2" + UNPACKED_FILE_SUFFIX); + list.add(item); + item = stubFactory.getArtifactItem(artifact); + item.setOverWrite("false"); + item.setIncludes("**/test3" + UNPACKED_FILE_SUFFIX); + list.add(item); + mojo.setArtifactItems(list); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); - assertMarkerFiles( mojo.getArtifactItems(), true ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); + assertMarkerFiles(mojo.getArtifactItems(), true); // Now run again and make sure the extracted files haven't gotten overwritten File destFile2 = - new File( mojo.getOutputDirectory().getAbsolutePath(), UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); + new File(mojo.getOutputDirectory().getAbsolutePath(), UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); File destFile3 = - new File( mojo.getOutputDirectory().getAbsolutePath(), UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + new File(mojo.getOutputDirectory().getAbsolutePath(), UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); long time = System.currentTimeMillis(); - time = time - ( time % 1000 ); - assertTrue( destFile2.setLastModified( time ) ); - assertTrue( destFile3.setLastModified( time ) ); - assertEquals( time, destFile2.lastModified() ); - assertEquals( time, destFile3.lastModified() ); - Thread.sleep( 100 ); + time = time - (time % 1000); + assertTrue(destFile2.setLastModified(time)); + assertTrue(destFile3.setLastModified(time)); + assertEquals(time, destFile2.lastModified()); + assertEquals(time, destFile3.lastModified()); + Thread.sleep(100); mojo.execute(); - assertEquals( time, destFile2.lastModified() ); - assertEquals( time, destFile3.lastModified() ); + assertEquals(time, destFile2.lastModified()); + assertEquals(time, destFile3.lastModified()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java index 765902909..fa147079e 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromConfiguration; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,16 +7,24 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromConfiguration; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; @@ -30,496 +36,430 @@ import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.apache.maven.project.MavenProject; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -public class TestUnpackMojo - extends AbstractDependencyMojoTestCase -{ +public class TestUnpackMojo extends AbstractDependencyMojoTestCase { UnpackMojo mojo; - protected void setUp() - throws Exception - { - super.setUp( "unpack", true, false ); + protected void setUp() throws Exception { + super.setUp("unpack", true, false); - File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-test/plugin-config.xml" ); - mojo = (UnpackMojo) lookupMojo( "unpack", testPom ); - mojo.setOutputDirectory( new File( this.testDir, "outputDirectory" ) ); - mojo.setMarkersDirectory( new File( this.testDir, "markers" ) ); - mojo.setSilent( true ); + File testPom = new File(getBasedir(), "target/test-classes/unit/unpack-test/plugin-config.xml"); + mojo = (UnpackMojo) lookupMojo("unpack", testPom); + mojo.setOutputDirectory(new File(this.testDir, "outputDirectory")); + mojo.setMarkersDirectory(new File(this.testDir, "markers")); + mojo.setSilent(true); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); // MavenProject project = mojo.getProject(); // init classifier things // it needs to get the archivermanager - stubFactory.setUnpackableFile( mojo.getArchiverManager() ); + stubFactory.setUnpackableFile(mojo.getArchiverManager()); // i'm using one file repeatedly to archive so I can test the name // programmatically. - stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar - + "target/test-classes/unit/unpack-dependencies-test/test.txt" ) ); + stubFactory.setSrcFile(new File( + getBasedir() + File.separatorChar + "target/test-classes/unit/unpack-dependencies-test/test.txt")); - mojo.setUseJvmChmod( true ); + mojo.setUseJvmChmod(true); - MavenSession session = newMavenSession( mojo.getProject() ); - setVariableValueToObject( mojo, "session", session ); + MavenSession session = newMavenSession(mojo.getProject()); + setVariableValueToObject(mojo, "session", session); - LegacySupport legacySupport = lookup( LegacySupport.class ); + LegacySupport legacySupport = lookup(LegacySupport.class); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); + legacySupport.setSession(session); + installLocalRepository(legacySupport); } - public ArtifactItem getSingleArtifactItem( boolean removeVersion ) - throws MojoExecutionException - { - List list = mojo.getProcessedArtifactItems( removeVersion ); - return list.get( 0 ); + public ArtifactItem getSingleArtifactItem(boolean removeVersion) throws MojoExecutionException { + List list = mojo.getProcessedArtifactItems(removeVersion); + return list.get(0); } - public void testGetArtifactItems() - throws Exception - { + public void testGetArtifactItems() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifact" ); - item.setGroupId( "groupId" ); - item.setVersion( "1.0" ); + item.setArtifactId("artifact"); + item.setGroupId("groupId"); + item.setVersion("1.0"); - ArrayList list = new ArrayList<>( 1 ); - list.add( createArtifact( item ) ); + ArrayList list = new ArrayList<>(1); + list.add(createArtifact(item)); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - ArtifactItem result = getSingleArtifactItem( false ); - assertEquals( mojo.getOutputDirectory(), result.getOutputDirectory() ); + ArtifactItem result = getSingleArtifactItem(false); + assertEquals(mojo.getOutputDirectory(), result.getOutputDirectory()); - File output = new File( mojo.getOutputDirectory(), "override" ); - item.setOutputDirectory( output ); - result = getSingleArtifactItem( false ); - assertEquals( output, result.getOutputDirectory() ); + File output = new File(mojo.getOutputDirectory(), "override"); + item.setOutputDirectory(output); + result = getSingleArtifactItem(false); + assertEquals(output, result.getOutputDirectory()); } - public void assertMarkerFiles( Collection items, boolean exist ) - { - for ( ArtifactItem item : items ) - { - assertMarkerFile( exist, item ); + public void assertMarkerFiles(Collection items, boolean exist) { + for (ArtifactItem item : items) { + assertMarkerFile(exist, item); } } - public void assertMarkerFile( boolean val, ArtifactItem item ) - { - UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler( item, mojo.getMarkersDirectory() ); - try - { - assertEquals( val, handle.isMarkerSet() ); - } - catch ( MojoExecutionException e ) - { - fail( e.getLongMessage() ); + public void assertMarkerFile(boolean val, ArtifactItem item) { + UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler(item, mojo.getMarkersDirectory()); + try { + assertEquals(val, handle.isMarkerSet()); + } catch (MojoExecutionException e) { + fail(e.getLongMessage()); } } - public void testUnpackFile() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testUnpackFile() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); mojo.execute(); - assertMarkerFiles( list, true ); + assertMarkerFiles(list, true); } - public void testSkip() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + public void testSkip() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); - mojo.setSkip( true ); - mojo.setArtifactItems( list ); + mojo.setSkip(true); + mojo.setArtifactItems(list); mojo.execute(); - assertMarkerFiles( list, false ); + assertMarkerFiles(list, false); } - public void testUnpackToLocation() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); + public void testUnpackToLocation() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); + ArtifactItem item = list.get(0); + item.setOutputDirectory(new File(mojo.getOutputDirectory(), "testOverride")); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); mojo.execute(); - assertMarkerFiles( list, true ); + assertMarkerFiles(list, true); } - public void testUnpackToLocationWhereLocationCannotBeCreatedThrowsException() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); + public void testUnpackToLocationWhereLocationCannotBeCreatedThrowsException() throws Exception { + List list = stubFactory.getArtifactItems(stubFactory.getClassifiedArtifacts()); + ArtifactItem item = list.get(0); + item.setOutputDirectory(new File(mojo.getOutputDirectory(), "testOverride")); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); final File currentFile = mojo.getOutputDirectory(); // pretend that the output directory cannot be found event after mkdirs has been called by the mojo // ifor instance in the case when the outputDirectory cannot be created because of permissions on the // parent of the output directory - mojo.setOutputDirectory( new File( currentFile.getAbsolutePath() ) - { + mojo.setOutputDirectory(new File(currentFile.getAbsolutePath()) { private static final long serialVersionUID = -8559876942040177020L; @Override - public boolean exists() - { + public boolean exists() { // this file will always report that it does not exist return false; } - } ); - try - { + }); + try { mojo.execute(); - fail( "Expected Exception Here." ); - } - catch ( MojoExecutionException e ) - { + fail("Expected Exception Here."); + } catch (MojoExecutionException e) { // caught the expected exception. } } - public void testMissingVersionNotFound() - throws Exception - { + public void testMissingVersionNotFound() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); - try - { + try { mojo.execute(); - fail( "Expected Exception Here." ); - } - catch ( MojoExecutionException e ) - { + fail("Expected Exception Here."); + } catch (MojoExecutionException e) { // caught the expected exception. } } - public List getDependencyList( ArtifactItem item ) - { + public List getDependencyList(ArtifactItem item) { Dependency dep = new Dependency(); - dep.setArtifactId( item.getArtifactId() ); - dep.setClassifier( item.getClassifier() ); - dep.setGroupId( item.getGroupId() ); - dep.setType( item.getType() ); - dep.setVersion( "2.0-SNAPSHOT" ); + dep.setArtifactId(item.getArtifactId()); + dep.setClassifier(item.getClassifier()); + dep.setGroupId(item.getGroupId()); + dep.setType(item.getType()); + dep.setVersion("2.0-SNAPSHOT"); Dependency dep2 = new Dependency(); - dep2.setArtifactId( item.getArtifactId() ); - dep2.setClassifier( "classifier" ); - dep2.setGroupId( item.getGroupId() ); - dep2.setType( item.getType() ); - dep2.setVersion( "2.1" ); + dep2.setArtifactId(item.getArtifactId()); + dep2.setClassifier("classifier"); + dep2.setGroupId(item.getGroupId()); + dep2.setType(item.getType()); + dep2.setVersion("2.1"); - List list = new ArrayList<>( 2 ); - list.add( dep2 ); - list.add( dep ); + List list = new ArrayList<>(2); + list.add(dep2); + list.add(dep); return list; } - public void testMissingVersionFromDependencies() - throws Exception - { + public void testMissingVersionFromDependencies() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("jar"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createArtifacts(getDependencyList(item))); mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "2.0-SNAPSHOT", item.getVersion() ); + assertMarkerFile(true, item); + assertEquals("2.0-SNAPSHOT", item.getVersion()); } - public void testMissingVersionFromDependenciesWithClassifier() - throws Exception - { + public void testMissingVersionFromDependenciesWithClassifier() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "war" ); + item.setArtifactId("artifactId"); + item.setClassifier("classifier"); + item.setGroupId("groupId"); + item.setType("war"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createArtifacts(getDependencyList(item))); mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "2.1", item.getVersion() ); + assertMarkerFile(true, item); + assertEquals("2.1", item.getVersion()); } - public List getDependencyMgtList( ArtifactItem item ) - { + public List getDependencyMgtList(ArtifactItem item) { Dependency dep = new Dependency(); - dep.setArtifactId( item.getArtifactId() ); - dep.setClassifier( item.getClassifier() ); - dep.setGroupId( item.getGroupId() ); - dep.setType( item.getType() ); - dep.setVersion( "3.0-SNAPSHOT" ); + dep.setArtifactId(item.getArtifactId()); + dep.setClassifier(item.getClassifier()); + dep.setGroupId(item.getGroupId()); + dep.setType(item.getType()); + dep.setVersion("3.0-SNAPSHOT"); Dependency dep2 = new Dependency(); - dep2.setArtifactId( item.getArtifactId() ); - dep2.setClassifier( "classifier" ); - dep2.setGroupId( item.getGroupId() ); - dep2.setType( item.getType() ); - dep2.setVersion( "3.1" ); + dep2.setArtifactId(item.getArtifactId()); + dep2.setClassifier("classifier"); + dep2.setGroupId(item.getGroupId()); + dep2.setType(item.getType()); + dep2.setVersion("3.1"); - List list = new ArrayList<>( 2 ); - list.add( dep2 ); - list.add( dep ); + List list = new ArrayList<>(2); + list.add(dep2); + list.add(dep); return list; } - public void testMissingVersionFromDependencyMgt() - throws Exception - { + public void testMissingVersionFromDependencyMgt() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("jar"); MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createArtifacts(getDependencyList(item))); item = new ArtifactItem(); - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + item.setArtifactId("artifactId-2"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("jar"); List list = new ArrayList<>(); - list.add( item ); + list.add(item); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); + project.getDependencyManagement().setDependencies(createArtifacts(getDependencyMgtList(item))); mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "3.0-SNAPSHOT", item.getVersion() ); + assertMarkerFile(true, item); + assertEquals("3.0-SNAPSHOT", item.getVersion()); } - public void testMissingVersionFromDependencyMgtWithClassifier() - throws Exception - { + public void testMissingVersionFromDependencyMgtWithClassifier() throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + item.setArtifactId("artifactId"); + item.setClassifier("classifier"); + item.setGroupId("groupId"); + item.setType("jar"); MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + project.setDependencies(createArtifacts(getDependencyList(item))); item = new ArtifactItem(); - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); - - stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.0-SNAPSHOT" ), null, - "jar", "classifier", false ); - stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.1" ), null, "jar", - "classifier", false ); + item.setArtifactId("artifactId-2"); + item.setClassifier("classifier"); + item.setGroupId("groupId"); + item.setType("jar"); + + stubFactory.createArtifact( + "groupId", + "artifactId-2", + VersionRange.createFromVersion("3.0-SNAPSHOT"), + null, + "jar", + "classifier", + false); + stubFactory.createArtifact( + "groupId", "artifactId-2", VersionRange.createFromVersion("3.1"), null, "jar", "classifier", false); List list = new ArrayList<>(); - list.add( item ); + list.add(item); - mojo.setArtifactItems( list ); + mojo.setArtifactItems(list); - project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); + project.getDependencyManagement().setDependencies(createArtifacts(getDependencyMgtList(item))); mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "3.1", item.getVersion() ); + assertMarkerFile(true, item); + assertEquals("3.1", item.getVersion()); } - public void testArtifactNotFound() - throws Exception - { - dotestArtifactExceptions( false, true ); + public void testArtifactNotFound() throws Exception { + dotestArtifactExceptions(false, true); } - public void testArtifactResolutionException() - throws Exception - { - dotestArtifactExceptions( true, false ); + public void testArtifactResolutionException() throws Exception { + dotestArtifactExceptions(true, false); } - public void dotestArtifactExceptions( boolean are, boolean anfe ) - throws Exception - { + public void dotestArtifactExceptions(boolean are, boolean anfe) throws Exception { ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); - item.setVersion( "1.0" ); + item.setArtifactId("artifactId"); + item.setClassifier(""); + item.setGroupId("groupId"); + item.setType("type"); + item.setVersion("1.0"); List list = new ArrayList<>(); - list.add( item ); - mojo.setArtifactItems( list ); + list.add(item); + mojo.setArtifactItems(list); - try - { + try { mojo.execute(); - fail( "ExpectedException" ); - } - catch ( MojoExecutionException e ) - { - assertEquals( "Unable to find/resolve artifact.", e.getMessage() ); + fail("ExpectedException"); + } catch (MojoExecutionException e) { + assertEquals("Unable to find/resolve artifact.", e.getMessage()); } } - public void testNoArtifactItems() - { - try - { - mojo.getProcessedArtifactItems( false ); - fail( "Expected Exception" ); - } - catch ( MojoExecutionException e ) - { - assertEquals( "There are no artifactItems configured.", e.getMessage() ); + public void testNoArtifactItems() { + try { + mojo.getProcessedArtifactItems(false); + fail("Expected Exception"); + } catch (MojoExecutionException e) { + assertEquals("There are no artifactItems configured.", e.getMessage()); } - } - public void testUnpackDontOverWriteReleases() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testUnpackDontOverWriteReleases() throws Exception { + stubFactory.setCreateFiles(true); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( createArtifact( release ) ); + ArtifactItem item = new ArtifactItem(createArtifact(release)); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); + mojo.setOverWriteIfNewer(false); mojo.execute(); - assertUnpacked( item, false ); + assertUnpacked(item, false); } - public void testUnpackDontOverWriteSnapshots() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testUnpackDontOverWriteSnapshots() throws Exception { + stubFactory.setCreateFiles(true); Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(artifact.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); + ArtifactItem item = new ArtifactItem(createArtifact(artifact)); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); + mojo.setOverWriteIfNewer(false); mojo.execute(); - assertUnpacked( item, false ); + assertUnpacked(item, false); } - public void testUnpackOverWriteReleases() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testUnpackOverWriteReleases() throws Exception { + stubFactory.setCreateFiles(true); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( createArtifact( release ) ); + ArtifactItem item = new ArtifactItem(createArtifact(release)); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); - mojo.setOverWriteReleases( true ); + mojo.setOverWriteIfNewer(false); + mojo.setOverWriteReleases(true); mojo.execute(); - assertUnpacked( item, true ); + assertUnpacked(item, true); } - public void testUnpackOverWriteSnapshot() - throws Exception - { - stubFactory.setCreateFiles( true ); + public void testUnpackOverWriteSnapshot() throws Exception { + stubFactory.setCreateFiles(true); Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(artifact.getFile().setLastModified(System.currentTimeMillis() - 2000)); - ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); + ArtifactItem item = new ArtifactItem(createArtifact(artifact)); - List list = new ArrayList<>( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); + List list = new ArrayList<>(1); + list.add(item); + mojo.setArtifactItems(list); - mojo.setOverWriteIfNewer( false ); - mojo.setOverWriteReleases( false ); - mojo.setOverWriteSnapshots( true ); + mojo.setOverWriteIfNewer(false); + mojo.setOverWriteReleases(false); + mojo.setOverWriteSnapshots(true); mojo.execute(); - assertUnpacked( item, true ); + assertUnpacked(item, true); } /** @@ -528,113 +468,111 @@ public void testUnpackOverWriteSnapshot() * https://bugs.openjdk.java.net/browse/JDK-8177809 * */ - public void testUnpackOverWriteIfNewer() - throws Exception - { + public void testUnpackOverWriteIfNewer() throws Exception { final long now = System.currentTimeMillis(); - mojo.setSilent( false ); - stubFactory.setCreateFiles( true ); + mojo.setSilent(false); + stubFactory.setCreateFiles(true); Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( now - 20000 ) ); + assertTrue(artifact.getFile().setLastModified(now - 20000)); - ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); + ArtifactItem item = new ArtifactItem(createArtifact(artifact)); - List list = Collections.singletonList( item ); - mojo.setArtifactItems( list ); - mojo.setOverWriteIfNewer( true ); + List list = Collections.singletonList(item); + mojo.setArtifactItems(list); + mojo.setOverWriteIfNewer(true); mojo.execute(); - File unpackedFile = getUnpackedFile( item ); + File unpackedFile = getUnpackedFile(item); // round down to the last second long time = now; - time = time - ( time % 1000 ); + time = time - (time % 1000); // go back 10 more seconds for linux time -= 10000; // set to known value - assertTrue( unpackedFile.setLastModified( time ) ); + assertTrue(unpackedFile.setLastModified(time)); // set source to be newer about some seconds, // especially on macOS it shouldn't be smaller than 8s in order to mitigate flapping test - assertTrue( artifact.getFile().setLastModified( time + 8000 ) ); + assertTrue(artifact.getFile().setLastModified(time + 8000)); // manually set markerfile (must match getMarkerFile in DefaultMarkerFileHandler) - File marker = new File( mojo.getMarkersDirectory(), artifact.getId().replace( ':', '-' ) + ".marker" ); - assertTrue( marker.setLastModified( time ) ); + File marker = new File(mojo.getMarkersDirectory(), artifact.getId().replace(':', '-') + ".marker"); + assertTrue(marker.setLastModified(time)); mojo.execute(); - long markerLastModifiedMillis = Files.getLastModifiedTime( marker.toPath() ).toMillis(); - long unpackedFileLastModifiedMillis = Files.getLastModifiedTime( unpackedFile.toPath() ).toMillis(); + long markerLastModifiedMillis = + Files.getLastModifiedTime(marker.toPath()).toMillis(); + long unpackedFileLastModifiedMillis = + Files.getLastModifiedTime(unpackedFile.toPath()).toMillis(); - assertTrue( "unpackedFile '" + unpackedFile + "' lastModified() == " + markerLastModifiedMillis - + ": should be different", markerLastModifiedMillis != unpackedFileLastModifiedMillis ); + assertTrue( + "unpackedFile '" + unpackedFile + "' lastModified() == " + markerLastModifiedMillis + + ": should be different", + markerLastModifiedMillis != unpackedFileLastModifiedMillis); } - public void assertUnpacked( ArtifactItem item, boolean overWrite ) - throws Exception - { + public void assertUnpacked(ArtifactItem item, boolean overWrite) throws Exception { - File unpackedFile = getUnpackedFile( item ); + File unpackedFile = getUnpackedFile(item); - Thread.sleep( 100 ); + Thread.sleep(100); // round down to the last second long time = System.currentTimeMillis(); - time = time - ( time % 1000 ); - assertTrue( unpackedFile.setLastModified( time ) ); + time = time - (time % 1000); + assertTrue(unpackedFile.setLastModified(time)); - assertEquals( time, unpackedFile.lastModified() ); + assertEquals(time, unpackedFile.lastModified()); mojo.execute(); - if ( overWrite ) - { - assertTrue( time != unpackedFile.lastModified() ); - } - else - { - assertEquals( time, unpackedFile.lastModified() ); + if (overWrite) { + assertTrue(time != unpackedFile.lastModified()); + } else { + assertEquals(time, unpackedFile.lastModified()); } } - public File getUnpackedFile( ArtifactItem item ) - { - File unpackedFile = new File( item.getOutputDirectory(), - DependencyArtifactStubFactory.getUnpackableFileName( item.getArtifact() ) ); + public File getUnpackedFile(ArtifactItem item) { + File unpackedFile = new File( + item.getOutputDirectory(), DependencyArtifactStubFactory.getUnpackableFileName(item.getArtifact())); - assertTrue( unpackedFile.exists() ); + assertTrue(unpackedFile.exists()); return unpackedFile; - } // respects the createUnpackableFile flag of the ArtifactStubFactory - private List createArtifacts( List items ) - throws IOException - { - for ( Dependency item : items ) - { - String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); - stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), - VersionRange.createFromVersion( item.getVersion() ), null, item.getType(), - classifier, item.isOptional() ); + private List createArtifacts(List items) throws IOException { + for (Dependency item : items) { + String classifier = "".equals(item.getClassifier()) ? null : item.getClassifier(); + stubFactory.createArtifact( + item.getGroupId(), + item.getArtifactId(), + VersionRange.createFromVersion(item.getVersion()), + null, + item.getType(), + classifier, + item.isOptional()); } return items; } - private Artifact createArtifact( Artifact art ) - throws IOException - { - String classifier = "".equals( art.getClassifier() ) ? null : art.getClassifier(); - stubFactory.createArtifact( art.getGroupId(), art.getArtifactId(), - VersionRange.createFromVersion( art.getVersion() ), null, art.getType(), classifier, - art.isOptional() ); + private Artifact createArtifact(Artifact art) throws IOException { + String classifier = "".equals(art.getClassifier()) ? null : art.getClassifier(); + stubFactory.createArtifact( + art.getGroupId(), + art.getArtifactId(), + VersionRange.createFromVersion(art.getVersion()), + null, + art.getType(), + classifier, + art.isOptional()); return art; } - private ArtifactItem createArtifact( ArtifactItem item ) - throws IOException - { - String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); - stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), item.getVersion(), null, item.getType(), - classifier ); + private ArtifactItem createArtifact(ArtifactItem item) throws IOException { + String classifier = "".equals(item.getClassifier()) ? null : item.getClassifier(); + stubFactory.createArtifact( + item.getGroupId(), item.getArtifactId(), item.getVersion(), null, item.getType(), classifier); return item; } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestBuildClasspathMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestBuildClasspathMojo.java index cb66f318a..871e668e0 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestBuildClasspathMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestBuildClasspathMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.LegacySupport; @@ -29,145 +27,132 @@ import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.project.MavenProject; -public class TestBuildClasspathMojo - extends AbstractDependencyMojoTestCase -{ - +public class TestBuildClasspathMojo extends AbstractDependencyMojoTestCase { + private BuildClasspathMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "build-classpath", true ); - - File testPom = new File( getBasedir(), "target/test-classes/unit/build-classpath-test/plugin-config.xml" ); - mojo = (BuildClasspathMojo) lookupMojo( "build-classpath", testPom ); + super.setUp("build-classpath", true); + + File testPom = new File(getBasedir(), "target/test-classes/unit/build-classpath-test/plugin-config.xml"); + mojo = (BuildClasspathMojo) lookupMojo("build-classpath", testPom); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); } /** * Tests the proper discovery and configuration of the mojo. */ - public void testEnvironment() - throws Exception - { + public void testEnvironment() throws Exception { MavenProject project = mojo.getProject(); // mojo.silent = true; Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); mojo.execute(); - try - { + try { mojo.readClasspathFile(); - fail( "Expected an illegal Argument Exception" ); - } - catch ( IllegalArgumentException e ) - { + fail("Expected an illegal Argument Exception"); + } catch (IllegalArgumentException e) { // expected to catch this. } - mojo.setOutputFile( new File( testDir, "buildClasspath.txt" ) ); + mojo.setOutputFile(new File(testDir, "buildClasspath.txt")); mojo.execute(); String file = mojo.readClasspathFile(); - assertNotNull( file ); - assertTrue( file.length() > 0 ); + assertNotNull(file); + assertTrue(file.length() > 0); - assertTrue( file.contains( File.pathSeparator ) ); - assertTrue( file.contains( File.separator ) ); + assertTrue(file.contains(File.pathSeparator)); + assertTrue(file.contains(File.separator)); String fileSep = "#####"; String pathSep = "%%%%%"; - mojo.setFileSeparator( fileSep ); - mojo.setPathSeparator( pathSep ); + mojo.setFileSeparator(fileSep); + mojo.setPathSeparator(pathSep); mojo.execute(); file = mojo.readClasspathFile(); - assertNotNull( file ); - assertTrue( file.length() > 0 ); + assertNotNull(file); + assertTrue(file.length() > 0); - assertFalse( file.contains( File.pathSeparator ) ); - assertFalse( file.contains( File.separator ) ); - assertTrue( file.contains( fileSep ) ); - assertTrue( file.contains( pathSep ) ); + assertFalse(file.contains(File.pathSeparator)); + assertFalse(file.contains(File.separator)); + assertTrue(file.contains(fileSep)); + assertTrue(file.contains(pathSep)); - String propertyValue = project.getProperties().getProperty( "outputProperty" ); - assertNull( propertyValue ); - mojo.setOutputProperty( "outputProperty" ); + String propertyValue = project.getProperties().getProperty("outputProperty"); + assertNull(propertyValue); + mojo.setOutputProperty("outputProperty"); mojo.execute(); - propertyValue = project.getProperties().getProperty( "outputProperty" ); - assertNotNull( propertyValue ); - + propertyValue = project.getProperties().getProperty("outputProperty"); + assertNotNull(propertyValue); } - public void testPath() - throws Exception - { - MavenSession session = newMavenSession( mojo.getProject() ); - setVariableValueToObject( mojo, "session", session ); - - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); - + public void testPath() throws Exception { + MavenSession session = newMavenSession(mojo.getProject()); + setVariableValueToObject(mojo, "session", session); + + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + installLocalRepository(legacySupport); + Artifact artifact = stubFactory.getReleaseArtifact(); StringBuilder sb = new StringBuilder(); - mojo.setPrefix( null ); - mojo.setStripVersion( false ); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( artifact.getFile().getPath(), sb.toString() ); + mojo.setPrefix(null); + mojo.setStripVersion(false); + mojo.appendArtifactPath(artifact, sb); + assertEquals(artifact.getFile().getPath(), sb.toString()); - mojo.setLocalRepoProperty( "$M2_REPO" ); + mojo.setLocalRepoProperty("$M2_REPO"); sb = new StringBuilder(); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( "$M2_REPO" + File.separator + artifact.getFile().getName(), sb.toString() ); + mojo.appendArtifactPath(artifact, sb); + assertEquals("$M2_REPO" + File.separator + artifact.getFile().getName(), sb.toString()); - mojo.setLocalRepoProperty( "%M2_REPO%" ); + mojo.setLocalRepoProperty("%M2_REPO%"); sb = new StringBuilder(); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( "%M2_REPO%" + File.separator + artifact.getFile().getName(), sb.toString() ); + mojo.appendArtifactPath(artifact, sb); + assertEquals("%M2_REPO%" + File.separator + artifact.getFile().getName(), sb.toString()); - mojo.setLocalRepoProperty( "%M2_REPO%" ); + mojo.setLocalRepoProperty("%M2_REPO%"); sb = new StringBuilder(); - mojo.setPrependGroupId( true ); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( "If prefix is null, prependGroupId has no impact ", - "%M2_REPO%" + File.separator + DependencyUtil.getFormattedFileName( artifact, false, false ), - sb.toString() ); - - mojo.setLocalRepoProperty( "" ); - mojo.setPrefix( "prefix" ); + mojo.setPrependGroupId(true); + mojo.appendArtifactPath(artifact, sb); + assertEquals( + "If prefix is null, prependGroupId has no impact ", + "%M2_REPO%" + File.separator + DependencyUtil.getFormattedFileName(artifact, false, false), + sb.toString()); + + mojo.setLocalRepoProperty(""); + mojo.setPrefix("prefix"); sb = new StringBuilder(); - mojo.setPrependGroupId( true ); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( "prefix" + File.separator + DependencyUtil.getFormattedFileName( artifact, false, true ), - sb.toString() ); - mojo.setPrependGroupId( false ); - - mojo.setLocalRepoProperty( "" ); - mojo.setPrefix( "prefix" ); + mojo.setPrependGroupId(true); + mojo.appendArtifactPath(artifact, sb); + assertEquals( + "prefix" + File.separator + DependencyUtil.getFormattedFileName(artifact, false, true), sb.toString()); + mojo.setPrependGroupId(false); + + mojo.setLocalRepoProperty(""); + mojo.setPrefix("prefix"); sb = new StringBuilder(); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( "prefix" + File.separator + artifact.getFile().getName(), sb.toString() ); + mojo.appendArtifactPath(artifact, sb); + assertEquals("prefix" + File.separator + artifact.getFile().getName(), sb.toString()); - mojo.setPrefix( "prefix" ); - mojo.setStripVersion( true ); + mojo.setPrefix("prefix"); + mojo.setStripVersion(true); sb = new StringBuilder(); - mojo.appendArtifactPath( artifact, sb ); - assertEquals( "prefix" + File.separator + DependencyUtil.getFormattedFileName( artifact, true ), - sb.toString() ); - + mojo.appendArtifactPath(artifact, sb); + assertEquals("prefix" + File.separator + DependencyUtil.getFormattedFileName(artifact, true), sb.toString()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo.java index 842e6614f..bb92b2f63 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; @@ -37,64 +35,57 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.StringUtils; -public class TestCopyDependenciesMojo - extends AbstractDependencyMojoTestCase -{ +public class TestCopyDependenciesMojo extends AbstractDependencyMojoTestCase { CopyDependenciesMojo mojo; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "copy-dependencies", true, false ); + super.setUp("copy-dependencies", true, false); - File testPom = new File( getBasedir(), "target/test-classes/unit/copy-dependencies-test/plugin-config.xml" ); - mojo = (CopyDependenciesMojo) lookupMojo( "copy-dependencies", testPom ); - mojo.outputDirectory = new File( this.testDir, "outputDirectory" ); + File testPom = new File(getBasedir(), "target/test-classes/unit/copy-dependencies-test/plugin-config.xml"); + mojo = (CopyDependenciesMojo) lookupMojo("copy-dependencies", testPom); + mojo.outputDirectory = new File(this.testDir, "outputDirectory"); // mojo.silent = true; - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - MavenSession session = newMavenSession( project ); - setVariableValueToObject( mojo, "session", session ); + MavenSession session = newMavenSession(project); + setVariableValueToObject(mojo, "session", session); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + installLocalRepository(legacySupport); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); - mojo.markersDirectory = new File( this.testDir, "markers" ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); + mojo.markersDirectory = new File(this.testDir, "markers"); - ArtifactHandlerManager manager = lookup( ArtifactHandlerManager.class ); - setVariableValueToObject( mojo, "artifactHandlerManager", manager ); + ArtifactHandlerManager manager = lookup(ArtifactHandlerManager.class); + setVariableValueToObject(mojo, "artifactHandlerManager", manager); } - public void assertNoMarkerFile( Artifact artifact ) throws MojoExecutionException - { - DefaultFileMarkerHandler handle = new DefaultFileMarkerHandler( artifact, mojo.markersDirectory ); - assertFalse( handle.isMarkerSet() ); + public void assertNoMarkerFile(Artifact artifact) throws MojoExecutionException { + DefaultFileMarkerHandler handle = new DefaultFileMarkerHandler(artifact, mojo.markersDirectory); + assertFalse(handle.isMarkerSet()); } - public void testCopyFile() - throws MojoExecutionException, IOException - { - File src = File.createTempFile( "copy", null ); + public void testCopyFile() throws MojoExecutionException, IOException { + File src = File.createTempFile("copy", null); - File dest = new File( mojo.outputDirectory, "toMe.jar" ); + File dest = new File(mojo.outputDirectory, "toMe.jar"); - assertFalse( dest.exists() ); + assertFalse(dest.exists()); - copyFile( mojo, src, dest ); - assertTrue( dest.exists() ); + copyFile(mojo, src, dest); + assertTrue(dest.exists()); } /** @@ -102,104 +93,84 @@ public void testCopyFile() * * @throws Exception in case of an error */ - public void testMojo() - throws Exception - { + public void testMojo() throws Exception { mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertTrue(file.exists()); // there should be no markers for the copy mojo - assertNoMarkerFile( artifact ); + assertNoMarkerFile(artifact); } } - public void testStripVersion() - throws Exception - { + public void testStripVersion() throws Exception { mojo.stripVersion = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, true ); - File file = new File( mojo.outputDirectory, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, true); + File file = new File(mojo.outputDirectory, fileName); + assertTrue(file.exists()); } } - public void testStripClassifier() - throws Exception - { + public void testStripClassifier() throws Exception { mojo.stripClassifier = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false, false, false, true ); - File file = new File( mojo.outputDirectory, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false, false, false, true); + File file = new File(mojo.outputDirectory, fileName); + assertTrue(file.exists()); } } - public void testUseBaseVersion() - throws Exception - { + public void testUseBaseVersion() throws Exception { mojo.useBaseVersion = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false, false, true ); - File file = new File( mojo.outputDirectory, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false, false, true); + File file = new File(mojo.outputDirectory, fileName); + assertTrue(file.exists()); } } - public void testNoTransitive() - throws Exception - { + public void testNoTransitive() throws Exception { mojo.excludeTransitive = true; mojo.execute(); Set artifacts = mojo.getProject().getDependencyArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertTrue(file.exists()); } } - public void testExcludeType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeTypes = "jar"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getType().equalsIgnoreCase( "jar" ), !file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getType().equalsIgnoreCase("jar"), !file.exists()); } } - public void testIncludeType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeTypes = "jar"; mojo.excludeTypes = "jar"; @@ -208,47 +179,40 @@ public void testIncludeType() mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertFalse( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertFalse(file.exists()); } mojo.excludeTypes = ""; mojo.execute(); artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getType().equalsIgnoreCase( "jar" ), file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getType().equalsIgnoreCase("jar"), file.exists()); } } - public void testExcludeArtifactId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getArtifactArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeArtifactId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getArtifactArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeArtifactIds = "one"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getArtifactId().equals( "one" ), !file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getArtifactId().equals("one"), !file.exists()); } } - public void testIncludeArtifactId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getArtifactArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeArtifactId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getArtifactArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeArtifactIds = "one"; mojo.excludeArtifactIds = "one"; @@ -257,30 +221,26 @@ public void testIncludeArtifactId() mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertFalse( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertFalse(file.exists()); } mojo.excludeArtifactIds = ""; mojo.execute(); artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getArtifactId().equals( "one" ), file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getArtifactId().equals("one"), file.exists()); } } - public void testIncludeGroupId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getGroupIdArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeGroupId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getGroupIdArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeGroupIds = "one"; mojo.excludeGroupIds = "one"; // shouldn't get anything @@ -288,85 +248,71 @@ public void testIncludeGroupId() mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertFalse( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertFalse(file.exists()); } mojo.excludeGroupIds = ""; mojo.execute(); artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getGroupId().equals( "one" ), file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getGroupId().equals("one"), file.exists()); } - } - public void testExcludeGroupId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getGroupIdArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeGroupId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getGroupIdArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeGroupIds = "one"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( artifact.getGroupId().equals( "one" ), !file.exists() ); + assertEquals(artifact.getGroupId().equals("one"), !file.exists()); } } - public void testExcludeMultipleGroupIds() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getGroupIdArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeMultipleGroupIds() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getGroupIdArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeGroupIds = "one,two"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( artifact.getGroupId().equals( "one" ) || artifact.getGroupId().equals( "two" ), - !file.exists() ); + assertEquals( + artifact.getGroupId().equals("one") || artifact.getGroupId().equals("two"), !file.exists()); } } - public void testExcludeClassifier() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getClassifiedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeClassifier() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getClassifiedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeClassifiers = "one"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getClassifier().equals( "one" ), !file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getClassifier().equals("one"), !file.exists()); } } - public void testIncludeClassifier() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getClassifiedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeClassifier() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getClassifiedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeClassifiers = "one"; mojo.excludeClassifiers = "one"; @@ -375,127 +321,105 @@ public void testIncludeClassifier() mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertFalse( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertFalse(file.exists()); } mojo.excludeClassifiers = ""; mojo.execute(); artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getClassifier().equals( "one" ), file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getClassifier().equals("one"), file.exists()); } - } - public void testSubPerType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerType = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, true, false, false, false, false, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, true, false, false, false, false, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testCDMClassifier() - throws Exception - { - dotestClassifierType( "jdk14", null ); + public void testCDMClassifier() throws Exception { + dotestClassifierType("jdk14", null); } - public void testCDMType() - throws Exception - { - dotestClassifierType( null, "sources" ); + public void testCDMType() throws Exception { + dotestClassifierType(null, "sources"); } - public void testCDMClassifierType() - throws Exception - { - dotestClassifierType( "jdk14", "sources" ); + public void testCDMClassifierType() throws Exception { + dotestClassifierType("jdk14", "sources"); } - public void dotestClassifierType( String testClassifier, String testType ) - throws Exception - { + public void dotestClassifierType(String testClassifier, String testType) throws Exception { mojo.classifier = testClassifier; mojo.type = testType; - for ( Artifact artifact : mojo.getProject().getArtifacts() ) - { + for (Artifact artifact : mojo.getProject().getArtifacts()) { String type = testType != null ? testType : artifact.getType(); - stubFactory.createArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), - artifact.getScope(), type, testClassifier ); - + stubFactory.createArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + artifact.getScope(), + type, + testClassifier); } mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { String useClassifier = artifact.getClassifier(); String useType = artifact.getType(); - if ( StringUtils.isNotEmpty( testClassifier ) ) - { + if (StringUtils.isNotEmpty(testClassifier)) { useClassifier = "-" + testClassifier; // type is only used if classifier is used. - if ( StringUtils.isNotEmpty( testType ) ) - { + if (StringUtils.isNotEmpty(testType)) { useType = testType; } } String fileName = artifact.getArtifactId() + "-" + artifact.getVersion() + useClassifier + "." + useType; - File file = new File( mojo.outputDirectory, fileName ); + File file = new File(mojo.outputDirectory, fileName); - if ( !file.exists() ) - { - fail( "Can't find:" + file.getAbsolutePath() ); + if (!file.exists()) { + fail("Can't find:" + file.getAbsolutePath()); } // there should be no markers for the copy mojo - assertNoMarkerFile( artifact ); + assertNoMarkerFile(artifact); } } - public void testArtifactResolutionException() - throws MojoFailureException - { + public void testArtifactResolutionException() throws MojoFailureException { dotestArtifactExceptions(); } - public void dotestArtifactExceptions() - throws MojoFailureException - { + public void dotestArtifactExceptions() throws MojoFailureException { mojo.classifier = "jdk"; mojo.type = "java-sources"; - try - { + try { mojo.execute(); - fail( "ExpectedException" ); - } - catch ( MojoExecutionException e ) - { + fail("ExpectedException"); + } catch (MojoExecutionException e) { } } @@ -507,81 +431,75 @@ public void dotestArtifactExceptions() */ public void testDontOverWriteRelease() - throws MojoExecutionException, InterruptedException, IOException, MojoFailureException - { + throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); - artifacts.add( release ); + artifacts.add(release); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteIfNewer = false; mojo.execute(); - File copiedFile = new File( mojo.outputDirectory, DependencyUtil.getFormattedFileName( release, false ) ); + File copiedFile = new File(mojo.outputDirectory, DependencyUtil.getFormattedFileName(release, false)); - Thread.sleep( 100 ); + Thread.sleep(100); // round up to the next second long time = System.currentTimeMillis() + 1000; - time = time - ( time % 1000 ); - assertTrue( copiedFile.setLastModified( time ) ); - Thread.sleep( 100 ); + time = time - (time % 1000); + assertTrue(copiedFile.setLastModified(time)); + Thread.sleep(100); mojo.execute(); - assertEquals( time, copiedFile.lastModified() ); + assertEquals(time, copiedFile.lastModified()); } - public void testOverWriteRelease() - throws MojoExecutionException, IOException, MojoFailureException - { + public void testOverWriteRelease() throws MojoExecutionException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( 1000L ) ); - assertEquals( 1000L, release.getFile().lastModified() ); - - artifacts.add( release ); + assertTrue(release.getFile().setLastModified(1000L)); + assertEquals(1000L, release.getFile().lastModified()); + + artifacts.add(release); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = true; mojo.overWriteIfNewer = false; mojo.execute(); - File copiedFile = new File( mojo.outputDirectory, DependencyUtil.getFormattedFileName( release, false ) ); + File copiedFile = new File(mojo.outputDirectory, DependencyUtil.getFormattedFileName(release, false)); - assertTrue( copiedFile.setLastModified( 2000L ) ); - assertEquals( 2000L, copiedFile.lastModified() ); + assertTrue(copiedFile.setLastModified(2000L)); + assertEquals(2000L, copiedFile.lastModified()); mojo.execute(); long timeCopyNow = copiedFile.lastModified(); - assertEquals( 1000L, timeCopyNow ); - + assertEquals(1000L, timeCopyNow); } - public void testDontOverWriteSnap() - throws MojoExecutionException, IOException, MojoFailureException - { + public void testDontOverWriteSnap() throws MojoExecutionException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact snap = stubFactory.getSnapshotArtifact(); - assertTrue( snap.getFile().setLastModified( 1000L ) ); - assertEquals( 1000L, snap.getFile().lastModified() ); + assertTrue(snap.getFile().setLastModified(1000L)); + assertEquals(1000L, snap.getFile().lastModified()); - artifacts.add( snap ); + artifacts.add(snap); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = false; mojo.overWriteSnapshots = false; @@ -589,30 +507,28 @@ public void testDontOverWriteSnap() mojo.execute(); - File copiedFile = new File( mojo.outputDirectory, DependencyUtil.getFormattedFileName( snap, false ) ); + File copiedFile = new File(mojo.outputDirectory, DependencyUtil.getFormattedFileName(snap, false)); - assertTrue( copiedFile.setLastModified( 2000L ) ); - assertEquals( 2000L, copiedFile.lastModified() ); + assertTrue(copiedFile.setLastModified(2000L)); + assertEquals(2000L, copiedFile.lastModified()); mojo.execute(); long timeCopyNow = copiedFile.lastModified(); - assertEquals( 2000L, timeCopyNow ); + assertEquals(2000L, timeCopyNow); } - public void testOverWriteSnap() - throws MojoExecutionException, IOException, MojoFailureException - { + public void testOverWriteSnap() throws MojoExecutionException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact snap = stubFactory.getSnapshotArtifact(); - assertTrue( snap.getFile().setLastModified( 1000L ) ); - assertEquals( 1000L, snap.getFile().lastModified() ); + assertTrue(snap.getFile().setLastModified(1000L)); + assertEquals(1000L, snap.getFile().lastModified()); - artifacts.add( snap ); + artifacts.add(snap); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = false; mojo.overWriteSnapshots = true; @@ -620,158 +536,130 @@ public void testOverWriteSnap() mojo.execute(); - File copiedFile = new File( mojo.outputDirectory, DependencyUtil.getFormattedFileName( snap, false ) ); + File copiedFile = new File(mojo.outputDirectory, DependencyUtil.getFormattedFileName(snap, false)); - assertTrue( copiedFile.setLastModified( 2000L ) ); - assertEquals( 2000L, copiedFile.lastModified() ); + assertTrue(copiedFile.setLastModified(2000L)); + assertEquals(2000L, copiedFile.lastModified()); mojo.execute(); long timeCopyNow = copiedFile.lastModified(); - assertEquals( 1000L, timeCopyNow ); + assertEquals(1000L, timeCopyNow); } - public void testGetDependencies() - throws MojoExecutionException - { - assertEquals( mojo.getResolvedDependencies( true ).toString(), - mojo.getDependencySets( true ).getResolvedDependencies().toString() ); + public void testGetDependencies() throws MojoExecutionException { + assertEquals( + mojo.getResolvedDependencies(true).toString(), + mojo.getDependencySets(true).getResolvedDependencies().toString()); } - public void testExcludeProvidedScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeProvidedScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "provided"; // mojo.silent = false; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getScope().equals( "provided" ), !file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getScope().equals("provided"), !file.exists()); file.delete(); - assertFalse( file.exists() ); + assertFalse(file.exists()); } - } - public void testExcludeSystemScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeSystemScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "system"; // mojo.silent = false; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); - assertEquals( artifact.getScope().equals( "system" ), !file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); + assertEquals(artifact.getScope().equals("system"), !file.exists()); file.delete(); - assertFalse( file.exists() ); + assertFalse(file.exists()); } - } - public void testExcludeCompileScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeCompileScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "compile"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.excludeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.excludeScope); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( !saf.include( artifact ), file.exists() ); + assertEquals(!saf.include(artifact), file.exists()); } } - public void testExcludeTestScope() - throws IOException, MojoFailureException - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeTestScope() throws IOException, MojoFailureException { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "test"; - try - { + try { mojo.execute(); - fail( "expected an exception" ); - } - catch ( MojoExecutionException e ) - { + fail("expected an exception"); + } catch (MojoExecutionException e) { } - } - public void testExcludeRuntimeScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeRuntimeScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "runtime"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.excludeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.excludeScope); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( !saf.include( artifact ), file.exists() ); + assertEquals(!saf.include(artifact), file.exists()); } } - public void testCopyPom() - throws Exception - { - mojo.setCopyPom( true ); + public void testCopyPom() throws Exception { + mojo.setCopyPom(true); Set set = new HashSet<>(); - set.add( stubFactory.createArtifact( "org.apache.maven", "maven-artifact", "2.0.7", Artifact.SCOPE_COMPILE ) ); - stubFactory.createArtifact( "org.apache.maven", "maven-artifact", "2.0.7", Artifact.SCOPE_COMPILE, "pom", - null ); - mojo.getProject().setArtifacts( set ); + set.add(stubFactory.createArtifact("org.apache.maven", "maven-artifact", "2.0.7", Artifact.SCOPE_COMPILE)); + stubFactory.createArtifact("org.apache.maven", "maven-artifact", "2.0.7", Artifact.SCOPE_COMPILE, "pom", null); + mojo.getProject().setArtifacts(set); mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName.substring( 0, fileName.length() - 4 ) + ".pom" ); - assertTrue( file + " doesn't exist", file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName.substring(0, fileName.length() - 4) + ".pom"); + assertTrue(file + " doesn't exist", file.exists()); } } - public void testPrependGroupId() - throws Exception - { + public void testPrependGroupId() throws Exception { mojo.prependGroupId = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false, true ); - File file = new File( mojo.outputDirectory, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false, true); + File file = new File(mojo.outputDirectory, fileName); + assertTrue(file.exists()); } } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo2.java b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo2.java index 61b282d47..5ef9062e8 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo2.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestCopyDependenciesMojo2.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.io.IOException; @@ -27,7 +26,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -48,321 +46,282 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.StringUtils; -public class TestCopyDependenciesMojo2 - extends AbstractDependencyMojoTestCase -{ +public class TestCopyDependenciesMojo2 extends AbstractDependencyMojoTestCase { private CopyDependenciesMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "copy-dependencies", true ); + super.setUp("copy-dependencies", true); - File testPom = new File( getBasedir(), "target/test-classes/unit/copy-dependencies-test/plugin-config.xml" ); - mojo = (CopyDependenciesMojo) lookupMojo( "copy-dependencies", testPom ); - mojo.outputDirectory = new File( this.testDir, "outputDirectory" ); + File testPom = new File(getBasedir(), "target/test-classes/unit/copy-dependencies-test/plugin-config.xml"); + mojo = (CopyDependenciesMojo) lookupMojo("copy-dependencies", testPom); + mojo.outputDirectory = new File(this.testDir, "outputDirectory"); // mojo.silent = true; - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); - mojo.markersDirectory = new File( this.testDir, "markers" ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); + mojo.markersDirectory = new File(this.testDir, "markers"); - LegacySupport legacySupport = lookup( LegacySupport.class ); - MavenSession session = newMavenSession( project ); - setVariableValueToObject( mojo, "session", session ); + LegacySupport legacySupport = lookup(LegacySupport.class); + MavenSession session = newMavenSession(project); + setVariableValueToObject(mojo, "session", session); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); + legacySupport.setSession(session); + installLocalRepository(legacySupport); } - public void testCopyDependenciesMojoIncludeCompileScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testCopyDependenciesMojoIncludeCompileScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "compile"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.includeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.includeScope); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( saf.include( artifact ), file.exists() ); + assertEquals(saf.include(artifact), file.exists()); } } - public void testCopyDependenciesMojoIncludeTestScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testCopyDependenciesMojoIncludeTestScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "test"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.includeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.includeScope); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( saf.include( artifact ), file.exists() ); + assertEquals(saf.include(artifact), file.exists()); } } - public void testCopyDependenciesMojoIncludeRuntimeScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testCopyDependenciesMojoIncludeRuntimeScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "runtime"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.includeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.includeScope); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( saf.include( artifact ), file.exists() ); + assertEquals(saf.include(artifact), file.exists()); } } - public void testCopyDependenciesMojoIncludeprovidedScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testCopyDependenciesMojoIncludeprovidedScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "provided"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ), file.exists() ); + assertEquals(Artifact.SCOPE_PROVIDED.equals(artifact.getScope()), file.exists()); } } - public void testCopyDependenciesMojoIncludesystemScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testCopyDependenciesMojoIncludesystemScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "system"; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File file = new File( mojo.outputDirectory, fileName ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File file = new File(mojo.outputDirectory, fileName); - assertEquals( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ), file.exists() ); + assertEquals(Artifact.SCOPE_SYSTEM.equals(artifact.getScope()), file.exists()); } } - public void testSubPerArtifact() - throws Exception - { + public void testSubPerArtifact() throws Exception { mojo.useSubDirectoryPerArtifact = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, false, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, false, true, false, false, false, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testSubPerArtifactAndType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerArtifactAndType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerArtifact = true; mojo.useSubDirectoryPerType = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, false, false, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, true, true, false, false, false, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testSubPerArtifactAndScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerArtifactAndScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerArtifact = true; mojo.useSubDirectoryPerScope = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File folder = DependencyUtil.getFormattedOutputDirectory( true, false, true, false, false, false, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File folder = DependencyUtil.getFormattedOutputDirectory( + true, false, true, false, false, false, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testRepositoryLayout() - throws Exception - { + public void testRepositoryLayout() throws Exception { String baseVersion = "2.0-SNAPSHOT"; String groupId = "testGroupId"; String artifactId = "expanded-snapshot"; Artifact expandedSnapshot = - createExpandedVersionArtifact( baseVersion, groupId, artifactId, "compile", "jar", null ); + createExpandedVersionArtifact(baseVersion, groupId, artifactId, "compile", "jar", null); - mojo.getProject().getArtifacts().add( expandedSnapshot ); - mojo.getProject().getDependencyArtifacts().add( expandedSnapshot ); + mojo.getProject().getArtifacts().add(expandedSnapshot); + mojo.getProject().getDependencyArtifacts().add(expandedSnapshot); Artifact pomExpandedSnapshot = - createExpandedVersionArtifact( baseVersion, groupId, artifactId, "compile", "pom", null ); - mojo.getProject().getArtifacts().add( pomExpandedSnapshot ); - mojo.getProject().getDependencyArtifacts().add( pomExpandedSnapshot ); + createExpandedVersionArtifact(baseVersion, groupId, artifactId, "compile", "pom", null); + mojo.getProject().getArtifacts().add(pomExpandedSnapshot); + mojo.getProject().getDependencyArtifacts().add(pomExpandedSnapshot); mojo.useRepositoryLayout = true; mojo.execute(); - ArtifactFactory artifactFactory = lookup( ArtifactFactory.class ); + ArtifactFactory artifactFactory = lookup(ArtifactFactory.class); File outputDirectory = mojo.outputDirectory; - ArtifactRepository targetRepository = - new MavenArtifactRepository( "local", outputDirectory.toURI().toURL().toExternalForm(), - new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + ArtifactRepository targetRepository = new MavenArtifactRepository( + "local", + outputDirectory.toURI().toURL().toExternalForm(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); Set artifacts = mojo.getProject().getArtifacts(); - File baseDirectory = Paths.get( targetRepository.getBasedir() ).toFile(); - assertTrue( baseDirectory.isDirectory() ); - - for ( Artifact artifact : artifacts ) - { - assertArtifactExists( artifact, targetRepository ); - - if ( !artifact.getBaseVersion().equals( artifact.getVersion() ) ) - { - Artifact baseArtifact = artifactFactory.createArtifact( artifact.getGroupId(), artifact.getArtifactId(), - artifact.getBaseVersion(), artifact.getScope(), - artifact.getType() ); - assertArtifactExists( baseArtifact, targetRepository ); + File baseDirectory = Paths.get(targetRepository.getBasedir()).toFile(); + assertTrue(baseDirectory.isDirectory()); + + for (Artifact artifact : artifacts) { + assertArtifactExists(artifact, targetRepository); + + if (!artifact.getBaseVersion().equals(artifact.getVersion())) { + Artifact baseArtifact = artifactFactory.createArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getBaseVersion(), + artifact.getScope(), + artifact.getType()); + assertArtifactExists(baseArtifact, targetRepository); } - } } - private Artifact createExpandedVersionArtifact( String baseVersion, String groupId, String artifactId, String scope, - String type, String classifier ) - throws IOException - { - Artifact expandedSnapshot = - this.stubFactory.createArtifact( groupId, artifactId, VersionRange.createFromVersion( baseVersion ), scope, - type, classifier, false ); + private Artifact createExpandedVersionArtifact( + String baseVersion, String groupId, String artifactId, String scope, String type, String classifier) + throws IOException { + Artifact expandedSnapshot = this.stubFactory.createArtifact( + groupId, artifactId, VersionRange.createFromVersion(baseVersion), scope, type, classifier, false); Snapshot snapshot = new Snapshot(); - snapshot.setTimestamp( "20130710.122148" ); - snapshot.setBuildNumber( 1 ); - RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata( expandedSnapshot, snapshot ); + snapshot.setTimestamp("20130710.122148"); + snapshot.setBuildNumber(1); + RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(expandedSnapshot, snapshot); String newVersion = snapshot.getTimestamp() + "-" + snapshot.getBuildNumber(); - expandedSnapshot.setResolvedVersion( StringUtils.replace( baseVersion, Artifact.SNAPSHOT_VERSION, - newVersion ) ); - expandedSnapshot.addMetadata( metadata ); + expandedSnapshot.setResolvedVersion(StringUtils.replace(baseVersion, Artifact.SNAPSHOT_VERSION, newVersion)); + expandedSnapshot.addMetadata(metadata); return expandedSnapshot; } - private void assertArtifactExists( Artifact artifact, ArtifactRepository targetRepository ) - { - + private void assertArtifactExists(Artifact artifact, ArtifactRepository targetRepository) { + ArtifactRepositoryLayout layout = targetRepository.getLayout(); - String pathOf = layout.pathOf( artifact ); - - // possible change/bug in DefaultArtifactRepositoryLayout.pathOf method between Maven 3 and Maven 3.1 - pathOf = pathOf.replace( "20130710.122148-1", "SNAPSHOT" ); - - File file = new File( targetRepository.getBasedir(), pathOf ); - - Path targetPath = Paths.get( file.getParent() ); - assertTrue( "Target path doesn't exist: " + targetPath, Files.isDirectory( targetPath ) ); - - assertTrue( "File doesn't exist: " + file.getAbsolutePath(), file.exists() ); + String pathOf = layout.pathOf(artifact); + + // possible change/bug in DefaultArtifactRepositoryLayout.pathOf method between Maven 3 and Maven 3.1 + pathOf = pathOf.replace("20130710.122148-1", "SNAPSHOT"); + + File file = new File(targetRepository.getBasedir(), pathOf); + + Path targetPath = Paths.get(file.getParent()); + assertTrue("Target path doesn't exist: " + targetPath, Files.isDirectory(targetPath)); + + assertTrue("File doesn't exist: " + file.getAbsolutePath(), file.exists()); Collection metas = artifact.getMetadataList(); - for ( ArtifactMetadata meta : metas ) - { - File metaFile = - new File( targetRepository.getBasedir(), - layout.pathOfLocalRepositoryMetadata( meta, targetRepository ) ); - assertTrue( metaFile.exists() ); + for (ArtifactMetadata meta : metas) { + File metaFile = new File( + targetRepository.getBasedir(), layout.pathOfLocalRepositoryMetadata(meta, targetRepository)); + assertTrue(metaFile.exists()); } } - public void testSubPerArtifactRemoveVersion() - throws Exception - { + public void testSubPerArtifactRemoveVersion() throws Exception { mojo.useSubDirectoryPerArtifact = true; mojo.stripVersion = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, true ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, false, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, true); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, false, true, false, true, false, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testSubPerArtifactAndTypeRemoveVersion() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerArtifactAndTypeRemoveVersion() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerArtifact = true; mojo.useSubDirectoryPerType = true; mojo.stripVersion = true; @@ -370,40 +329,34 @@ public void testSubPerArtifactAndTypeRemoveVersion() mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, true ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, true, false, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, true); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, true, true, false, true, false, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testSubPerArtifactRemoveType() - throws Exception - { + public void testSubPerArtifactRemoveType() throws Exception { mojo.useSubDirectoryPerArtifact = true; mojo.stripType = true; mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, true, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, false, true, false, false, true, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - public void testSubPerArtifactAndTypeRemoveType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerArtifactAndTypeRemoveType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerArtifact = true; mojo.useSubDirectoryPerType = true; mojo.stripType = true; @@ -411,14 +364,12 @@ public void testSubPerArtifactAndTypeRemoveType() mojo.execute(); Set artifacts = mojo.getProject().getArtifacts(); - for ( Artifact artifact : artifacts ) - { - String fileName = DependencyUtil.getFormattedFileName( artifact, false ); - File folder = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, false, true, - mojo.outputDirectory, artifact ); - File file = new File( folder, fileName ); - assertTrue( file.exists() ); + for (Artifact artifact : artifacts) { + String fileName = DependencyUtil.getFormattedFileName(artifact, false); + File folder = DependencyUtil.getFormattedOutputDirectory( + false, true, true, false, false, true, mojo.outputDirectory, artifact); + File file = new File(folder, fileName); + assertTrue(file.exists()); } } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestIncludeExcludeUnpackDependenciesMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestIncludeExcludeUnpackDependenciesMojo.java index 5e582b7d1..377a557d0 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestIncludeExcludeUnpackDependenciesMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestIncludeExcludeUnpackDependenciesMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,26 +7,24 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; import org.apache.maven.project.MavenProject; -public class TestIncludeExcludeUnpackDependenciesMojo - extends AbstractDependencyMojoTestCase -{ +public class TestIncludeExcludeUnpackDependenciesMojo extends AbstractDependencyMojoTestCase { private final String PACKED_FILE = "test.zip"; private final String UNPACKED_FILE_PREFIX = "test"; @@ -39,154 +35,135 @@ public class TestIncludeExcludeUnpackDependenciesMojo private UnpackDependenciesMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "unpack-dependencies", true ); + super.setUp("unpack-dependencies", true); - File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-dependencies-test/plugin-config.xml" ); - mojo = (UnpackDependenciesMojo) lookupMojo( "unpack-dependencies", testPom ); - mojo.outputDirectory = new File( this.testDir, "outputDirectory" ); + File testPom = new File(getBasedir(), "target/test-classes/unit/unpack-dependencies-test/plugin-config.xml"); + mojo = (UnpackDependenciesMojo) lookupMojo("unpack-dependencies", testPom); + mojo.outputDirectory = new File(this.testDir, "outputDirectory"); // mojo.silent = true; // it needs to get the archivermanager // stubFactory.setUnpackableFile( mojo.getArchiverManager() ); // i'm using one file repeatedly to archive so I can test the name // programmatically. - stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar + PACKED_FILE_PATH ) ); + stubFactory.setSrcFile(new File(getBasedir() + File.separatorChar + PACKED_FILE_PATH)); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); - - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); - mojo.markersDirectory = new File( this.testDir, "markers" ); + artifacts.addAll(directArtifacts); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); + mojo.markersDirectory = new File(this.testDir, "markers"); } - protected void tearDown() - { + protected void tearDown() { super.tearDown(); mojo = null; System.gc(); } - private void assertUnpacked( boolean unpacked, String fileName ) - { - File destFile = new File( mojo.getOutputDirectory().getAbsolutePath(), fileName ); - assertEquals( unpacked, destFile.exists() ); + private void assertUnpacked(boolean unpacked, String fileName) { + File destFile = new File(mojo.getOutputDirectory().getAbsolutePath(), fileName); + assertEquals(unpacked, destFile.exists()); } /** * This test will validate that only the 1 and 11 files get unpacked - * + * * @throws Exception in case of errors */ - public void testUnpackIncludesManyFiles() - throws Exception - { - mojo.setIncludes( "**/*1" + UNPACKED_FILE_SUFFIX ); + public void testUnpackIncludesManyFiles() throws Exception { + mojo.setIncludes("**/*1" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** * This test will verify only the 2 file gets unpacked - * + * * @throws Exception in case of errors */ - public void testUnpackIncludesSingleFile() - throws Exception - { - mojo.setIncludes( "**/test2" + UNPACKED_FILE_SUFFIX ); + public void testUnpackIncludesSingleFile() throws Exception { + mojo.setIncludes("**/test2" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** * This test will verify all files get unpacked - * + * * @throws Exception in case of errors */ - public void testUnpackIncludesAllFiles() - throws Exception - { - mojo.setIncludes( "**/*" ); + public void testUnpackIncludesAllFiles() throws Exception { + mojo.setIncludes("**/*"); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** * This test will validate that only the 2 and 3 files get unpacked - * + * * @throws Exception in case of errors */ - public void testUnpackExcludesManyFiles() - throws Exception - { - mojo.setExcludes( "**/*1" + UNPACKED_FILE_SUFFIX ); + public void testUnpackExcludesManyFiles() throws Exception { + mojo.setExcludes("**/*1" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** * This test will verify only the 1, 11 & 3 files get unpacked - * + * * @throws Exception in case of errors */ - public void testUnpackExcludesSingleFile() - throws Exception - { - mojo.setExcludes( "**/test2" + UNPACKED_FILE_SUFFIX ); + public void testUnpackExcludesSingleFile() throws Exception { + mojo.setExcludes("**/test2" + UNPACKED_FILE_SUFFIX); mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } /** * This test will verify no files get unpacked - * + * * @throws Exception in case of errors */ - public void testUnpackExcludesAllFiles() - throws Exception - { - mojo.setExcludes( "**/*" ); + public void testUnpackExcludesAllFiles() throws Exception { + mojo.setExcludes("**/*"); mojo.execute(); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(false, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } - public void testNoIncludeExcludes() - throws Exception - { + public void testNoIncludeExcludes() throws Exception { mojo.execute(); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX ); - assertUnpacked( true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX ); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 1 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 11 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 2 + UNPACKED_FILE_SUFFIX); + assertUnpacked(true, UNPACKED_FILE_PREFIX + 3 + UNPACKED_FILE_SUFFIX); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo.java index 5fa692e18..708832b12 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,22 +7,22 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; @@ -40,9 +38,7 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.StringUtils; -public class TestUnpackDependenciesMojo - extends AbstractDependencyMojoTestCase -{ +public class TestUnpackDependenciesMojo extends AbstractDependencyMojoTestCase { private final String UNPACKABLE_FILE = "test.txt"; @@ -50,209 +46,174 @@ public class TestUnpackDependenciesMojo UnpackDependenciesMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "unpack-dependencies", true, false ); + super.setUp("unpack-dependencies", true, false); - File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-dependencies-test/plugin-config.xml" ); - mojo = (UnpackDependenciesMojo) lookupMojo( "unpack-dependencies", testPom ); - mojo.outputDirectory = new File( this.testDir, "outputDirectory" ); - mojo.setUseJvmChmod( true ); + File testPom = new File(getBasedir(), "target/test-classes/unit/unpack-dependencies-test/plugin-config.xml"); + mojo = (UnpackDependenciesMojo) lookupMojo("unpack-dependencies", testPom); + mojo.outputDirectory = new File(this.testDir, "outputDirectory"); + mojo.setUseJvmChmod(true); // mojo.silent = true; // it needs to get the archivermanager - stubFactory.setUnpackableFile( mojo.getArchiverManager() ); + stubFactory.setUnpackableFile(mojo.getArchiverManager()); // i'm using one file repeatedly to archive so I can test the name // programmatically. - stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar + UNPACKABLE_FILE_PATH ) ); + stubFactory.setSrcFile(new File(getBasedir() + File.separatorChar + UNPACKABLE_FILE_PATH)); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - MavenSession session = newMavenSession( project ); - setVariableValueToObject( mojo, "session", session ); + MavenSession session = newMavenSession(project); + setVariableValueToObject(mojo, "session", session); + + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + installLocalRepository(legacySupport); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - installLocalRepository( legacySupport ); - Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); - mojo.markersDirectory = new File( this.testDir, "markers" ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); + mojo.markersDirectory = new File(this.testDir, "markers"); - ArtifactHandlerManager manager = lookup( ArtifactHandlerManager.class ); - setVariableValueToObject( mojo, "artifactHandlerManager", manager ); + ArtifactHandlerManager manager = lookup(ArtifactHandlerManager.class); + setVariableValueToObject(mojo, "artifactHandlerManager", manager); } - protected void tearDown() - { + protected void tearDown() { super.tearDown(); mojo = null; System.gc(); } - public void assertUnpacked( Artifact artifact ) - { - assertUnpacked( true, artifact ); + public void assertUnpacked(Artifact artifact) { + assertUnpacked(true, artifact); } - public void assertUnpacked( boolean val, Artifact artifact ) - { - File folder = - DependencyUtil.getFormattedOutputDirectory( mojo.useSubDirectoryPerScope, mojo.useSubDirectoryPerType, - mojo.useSubDirectoryPerArtifact, mojo.useRepositoryLayout, - mojo.stripVersion, mojo.stripType, mojo.outputDirectory, artifact ); + public void assertUnpacked(boolean val, Artifact artifact) { + File folder = DependencyUtil.getFormattedOutputDirectory( + mojo.useSubDirectoryPerScope, + mojo.useSubDirectoryPerType, + mojo.useSubDirectoryPerArtifact, + mojo.useRepositoryLayout, + mojo.stripVersion, + mojo.stripType, + mojo.outputDirectory, + artifact); - File destFile = new File( folder, DependencyArtifactStubFactory.getUnpackableFileName( artifact ) ); + File destFile = new File(folder, DependencyArtifactStubFactory.getUnpackableFileName(artifact)); - assertEquals( val, destFile.exists() ); - assertMarkerFile( val, artifact ); + assertEquals(val, destFile.exists()); + assertMarkerFile(val, artifact); } - public void assertMarkerFile( boolean val, Artifact artifact ) - { - DefaultFileMarkerHandler handle = new DefaultFileMarkerHandler( artifact, mojo.markersDirectory ); - try - { - assertEquals( val, handle.isMarkerSet() ); - } - catch ( MojoExecutionException e ) - { - fail( e.getLongMessage() ); + public void assertMarkerFile(boolean val, Artifact artifact) { + DefaultFileMarkerHandler handle = new DefaultFileMarkerHandler(artifact, mojo.markersDirectory); + try { + assertEquals(val, handle.isMarkerSet()); + } catch (MojoExecutionException e) { + fail(e.getLongMessage()); } } - public void testMojo() - throws Exception - { + public void testMojo() throws Exception { mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(artifact); } } - public void testNoTransitive() - throws Exception - { + public void testNoTransitive() throws Exception { mojo.excludeTransitive = true; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getDependencyArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getDependencyArtifacts()) { + assertUnpacked(artifact); } } - public void testExcludeType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArchiveArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArchiveArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeTypes = "jar"; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !artifact.getType().equalsIgnoreCase( "jar" ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!artifact.getType().equalsIgnoreCase("jar"), artifact); } } - public void testExcludeProvidedScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeProvidedScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "provided"; // mojo.silent = false; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !artifact.getScope().equals( "provided" ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!artifact.getScope().equals("provided"), artifact); } - } - public void testExcludeSystemScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeSystemScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "system"; // mojo.silent = false; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !artifact.getScope().equals( "system" ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!artifact.getScope().equals("system"), artifact); } - } - public void testExcludeCompileScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeCompileScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "compile"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.excludeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.excludeScope); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !saf.include( artifact ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!saf.include(artifact), artifact); } } - public void testExcludeTestScope() - throws IOException, MojoFailureException - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeTestScope() throws IOException, MojoFailureException { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "test"; - try - { + try { mojo.execute(); - fail( "expected an exception" ); - } - catch ( MojoExecutionException e ) - { + fail("expected an exception"); + } catch (MojoExecutionException e) { } - } - public void testExcludeRuntimeScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeRuntimeScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeScope = "runtime"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.excludeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.excludeScope); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !saf.include( artifact ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!saf.include(artifact), artifact); } } - public void testIncludeType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArchiveArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArchiveArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeTypes = "jar"; mojo.excludeTypes = "jar"; @@ -261,175 +222,141 @@ public void testIncludeType() mojo.execute(); Iterator iter = mojo.getProject().getArtifacts().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); - assertUnpacked( false, artifact ); + assertUnpacked(false, artifact); } mojo.excludeTypes = ""; mojo.execute(); iter = mojo.getProject().getArtifacts().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); - assertUnpacked( artifact.getType().equalsIgnoreCase( "jar" ), artifact ); + assertUnpacked(artifact.getType().equalsIgnoreCase("jar"), artifact); } } - public void testSubPerType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArchiveArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArchiveArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerType = true; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(artifact); } } - public void testSubPerArtifact() - throws Exception - { + public void testSubPerArtifact() throws Exception { mojo.useSubDirectoryPerArtifact = true; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(artifact); } } - public void testSubPerArtifactAndType() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArchiveArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerArtifactAndType() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArchiveArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerArtifact = true; mojo.useSubDirectoryPerType = true; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(artifact); } } - public void testSubPerArtifactRemoveVersion() - throws Exception - { + public void testSubPerArtifactRemoveVersion() throws Exception { mojo.useSubDirectoryPerArtifact = true; mojo.stripVersion = true; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(artifact); } } - public void testSubPerArtifactAndTypeRemoveVersion() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getTypedArchiveArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testSubPerArtifactAndTypeRemoveVersion() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getTypedArchiveArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.useSubDirectoryPerArtifact = true; mojo.useSubDirectoryPerType = true; mojo.stripVersion = true; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(artifact); } } - public void testIncludeCompileScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeCompileScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "compile"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.includeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.includeScope); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( saf.include( artifact ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(saf.include(artifact), artifact); } } - public void testIncludeTestScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeTestScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "test"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.includeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.includeScope); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( saf.include( artifact ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(saf.include(artifact), artifact); } } - public void testIncludeRuntimeScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeRuntimeScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "runtime"; mojo.execute(); - ScopeArtifactFilter saf = new ScopeArtifactFilter( mojo.includeScope ); + ScopeArtifactFilter saf = new ScopeArtifactFilter(mojo.includeScope); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( saf.include( artifact ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(saf.include(artifact), artifact); } } - public void testIncludeprovidedScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeprovidedScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "provided"; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(Artifact.SCOPE_PROVIDED.equals(artifact.getScope()), artifact); } } - public void testIncludesystemScope() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getScopedArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludesystemScope() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getScopedArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeScope = "system"; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(Artifact.SCOPE_SYSTEM.equals(artifact.getScope()), artifact); } } - public void testIncludeArtifactId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getArtifactArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeArtifactId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getArtifactArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeArtifactIds = "one"; mojo.excludeArtifactIds = "one"; @@ -437,59 +364,48 @@ public void testIncludeArtifactId() mojo.execute(); Iterator iter = mojo.getProject().getArtifacts().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); - assertUnpacked( false, artifact ); + assertUnpacked(false, artifact); } mojo.excludeArtifactIds = ""; mojo.execute(); iter = mojo.getProject().getArtifacts().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); - assertUnpacked( artifact.getArtifactId().equals( "one" ), artifact ); + assertUnpacked(artifact.getArtifactId().equals("one"), artifact); } - } - public void testExcludeArtifactId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getArtifactArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeArtifactId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getArtifactArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeArtifactIds = "one"; mojo.execute(); // test - get all direct dependencies and verify that they exist if they // do not have a classifier of "one" // then delete the file and at the end, verify the folder is empty. - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !artifact.getArtifactId().equals( "one" ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!artifact.getArtifactId().equals("one"), artifact); } } - public void testExcludeGroupId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getGroupIdArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testExcludeGroupId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getGroupIdArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.excludeGroupIds = "one"; mojo.execute(); - for ( Artifact artifact : (Iterable) mojo.getProject().getArtifacts() ) - { - assertUnpacked( !artifact.getGroupId().equals( "one" ), artifact ); + for (Artifact artifact : (Iterable) mojo.getProject().getArtifacts()) { + assertUnpacked(!artifact.getGroupId().equals("one"), artifact); } } - public void testIncludeGroupId() - throws Exception - { - mojo.getProject().setArtifacts( stubFactory.getGroupIdArtifacts() ); - mojo.getProject().setDependencyArtifacts( new HashSet() ); + public void testIncludeGroupId() throws Exception { + mojo.getProject().setArtifacts(stubFactory.getGroupIdArtifacts()); + mojo.getProject().setDependencyArtifacts(new HashSet()); mojo.includeGroupIds = "one"; mojo.excludeGroupIds = "one"; // shouldn't get anything @@ -497,150 +413,133 @@ public void testIncludeGroupId() mojo.execute(); Iterator iter = mojo.getProject().getArtifacts().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); // Testing with artifact id because group id is not in filename - assertUnpacked( false, artifact ); + assertUnpacked(false, artifact); } mojo.excludeGroupIds = ""; mojo.execute(); iter = mojo.getProject().getArtifacts().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = iter.next(); // Testing with artifact id because group id is not in filename - assertUnpacked( artifact.getGroupId().equals( "one" ), artifact ); + assertUnpacked(artifact.getGroupId().equals("one"), artifact); } - } - public void testCDMClassifier() - throws Exception - { - dotestClassifierType( "jdk14", null ); + public void testCDMClassifier() throws Exception { + dotestClassifierType("jdk14", null); } - public void testCDMType() - throws Exception - { - dotestClassifierType( null, "zip" ); + public void testCDMType() throws Exception { + dotestClassifierType(null, "zip"); } - public void testCDMClassifierType() - throws Exception - { - dotestClassifierType( "jdk14", "war" ); + public void testCDMClassifierType() throws Exception { + dotestClassifierType("jdk14", "war"); } - public void dotestClassifierType( String testClassifier, String testType ) - throws Exception - { + public void dotestClassifierType(String testClassifier, String testType) throws Exception { mojo.classifier = testClassifier; mojo.type = testType; - for ( Artifact artifact : mojo.getProject().getArtifacts() ) - { + for (Artifact artifact : mojo.getProject().getArtifacts()) { String type = testType != null ? testType : artifact.getType(); - this.stubFactory.createArtifact( artifact.getGroupId(), artifact.getArtifactId(), - VersionRange.createFromVersion( artifact.getBaseVersion() ), - artifact.getScope(), type, testClassifier, false ); + this.stubFactory.createArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + VersionRange.createFromVersion(artifact.getBaseVersion()), + artifact.getScope(), + type, + testClassifier, + false); } mojo.execute(); - for ( Artifact artifact : mojo.getProject().getArtifacts() ) - { + for (Artifact artifact : mojo.getProject().getArtifacts()) { String useClassifier = artifact.getClassifier(); String useType = artifact.getType(); - if ( StringUtils.isNotEmpty( testClassifier ) ) - { + if (StringUtils.isNotEmpty(testClassifier)) { useClassifier = testClassifier; // type is only used if classifier is used. - if ( StringUtils.isNotEmpty( testType ) ) - { + if (StringUtils.isNotEmpty(testType)) { useType = testType; } } - Artifact unpacked = - stubFactory.createArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), - Artifact.SCOPE_COMPILE, useType, useClassifier ); - assertUnpacked( unpacked ); + Artifact unpacked = stubFactory.createArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + Artifact.SCOPE_COMPILE, + useType, + useClassifier); + assertUnpacked(unpacked); } } - public void testArtifactNotFound() - throws Exception - { - dotestArtifactExceptions( false, true ); + public void testArtifactNotFound() throws Exception { + dotestArtifactExceptions(false, true); } - public void testArtifactResolutionException() - throws Exception - { - dotestArtifactExceptions( true, false ); + public void testArtifactResolutionException() throws Exception { + dotestArtifactExceptions(true, false); } - public void dotestArtifactExceptions( boolean are, boolean anfe ) - throws Exception - { + public void dotestArtifactExceptions(boolean are, boolean anfe) throws Exception { mojo.classifier = "jdk"; mojo.type = "java-sources"; - try - { + try { mojo.execute(); - fail( "ExpectedException" ); - } - catch ( MojoExecutionException e ) - { - } - } - - public File getUnpackedFile( Artifact artifact ) - { - File destDir = - DependencyUtil.getFormattedOutputDirectory( mojo.isUseSubDirectoryPerScope(), - mojo.isUseSubDirectoryPerType(), - mojo.isUseSubDirectoryPerArtifact(), mojo.useRepositoryLayout, - mojo.stripVersion, mojo.stripType, mojo.getOutputDirectory(), artifact ); - File unpacked = new File( destDir, DependencyArtifactStubFactory.getUnpackableFileName( artifact ) ); - assertTrue( unpacked.exists() ); + fail("ExpectedException"); + } catch (MojoExecutionException e) { + } + } + + public File getUnpackedFile(Artifact artifact) { + File destDir = DependencyUtil.getFormattedOutputDirectory( + mojo.isUseSubDirectoryPerScope(), + mojo.isUseSubDirectoryPerType(), + mojo.isUseSubDirectoryPerArtifact(), + mojo.useRepositoryLayout, + mojo.stripVersion, + mojo.stripType, + mojo.getOutputDirectory(), + artifact); + File unpacked = new File(destDir, DependencyArtifactStubFactory.getUnpackableFileName(artifact)); + assertTrue(unpacked.exists()); return unpacked; } - public DefaultFileMarkerHandler getUnpackedMarkerHandler( Artifact artifact ) - { - return new DefaultFileMarkerHandler( artifact, mojo.getMarkersDirectory() ); + public DefaultFileMarkerHandler getUnpackedMarkerHandler(Artifact artifact) { + return new DefaultFileMarkerHandler(artifact, mojo.getMarkersDirectory()); } - public void assertUnpacked( Artifact artifact, boolean overWrite ) - throws InterruptedException, MojoExecutionException, MojoFailureException - { - File unpackedFile = getUnpackedFile( artifact ); + public void assertUnpacked(Artifact artifact, boolean overWrite) + throws InterruptedException, MojoExecutionException, MojoFailureException { + File unpackedFile = getUnpackedFile(artifact); - Thread.sleep( 100 ); + Thread.sleep(100); // round down to the last second long time = System.currentTimeMillis(); - time = time - ( time % 1000 ); - assertTrue( unpackedFile.setLastModified( time ) ); + time = time - (time % 1000); + assertTrue(unpackedFile.setLastModified(time)); // wait at least a second for filesystems that only record to the // nearest second. - Thread.sleep( 1000 ); + Thread.sleep(1000); - assertEquals( time, unpackedFile.lastModified() ); + assertEquals(time, unpackedFile.lastModified()); mojo.execute(); - if ( overWrite ) - { - assertTrue( time != unpackedFile.lastModified() ); - } - else - { - assertEquals( time, unpackedFile.lastModified() ); + if (overWrite) { + assertTrue(time != unpackedFile.lastModified()); + } else { + assertEquals(time, unpackedFile.lastModified()); } } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo2.java b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo2.java index f4f4a3593..e841643f5 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo2.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesMojo2.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.fromDependencies; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,33 +7,30 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.fromDependencies; -import org.apache.maven.plugin.MojoFailureException; - +import java.io.File; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.project.MavenProject; -import java.io.File; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -public class TestUnpackDependenciesMojo2 - extends AbstractDependencyMojoTestCase -{ +public class TestUnpackDependenciesMojo2 extends AbstractDependencyMojoTestCase { private final String UNPACKABLE_FILE = "test.txt"; @@ -43,111 +38,107 @@ public class TestUnpackDependenciesMojo2 private UnpackDependenciesMojo mojo; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "unpack-dependencies", true ); + super.setUp("unpack-dependencies", true); - File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-dependencies-test/plugin-config.xml" ); - mojo = (UnpackDependenciesMojo) lookupMojo( "unpack-dependencies", testPom ); - mojo.outputDirectory = new File( this.testDir, "outputDirectory" ); - mojo.setUseJvmChmod( true ); + File testPom = new File(getBasedir(), "target/test-classes/unit/unpack-dependencies-test/plugin-config.xml"); + mojo = (UnpackDependenciesMojo) lookupMojo("unpack-dependencies", testPom); + mojo.outputDirectory = new File(this.testDir, "outputDirectory"); + mojo.setUseJvmChmod(true); // mojo.silent = true; // it needs to get the archivermanager - stubFactory.setUnpackableFile( mojo.getArchiverManager() ); + stubFactory.setUnpackableFile(mojo.getArchiverManager()); // i'm using one file repeatedly to archive so I can test the name // programmatically. - stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar + UNPACKABLE_FILE_PATH ) ); + stubFactory.setSrcFile(new File(getBasedir() + File.separatorChar + UNPACKABLE_FILE_PATH)); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); - - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); - mojo.markersDirectory = new File( this.testDir, "markers" ); + artifacts.addAll(directArtifacts); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); + mojo.markersDirectory = new File(this.testDir, "markers"); } - protected void tearDown() - { + protected void tearDown() { super.tearDown(); mojo = null; System.gc(); } - public File getUnpackedFile( Artifact artifact ) - { - File destDir = - DependencyUtil.getFormattedOutputDirectory( mojo.isUseSubDirectoryPerScope(), - mojo.isUseSubDirectoryPerType(), - mojo.isUseSubDirectoryPerArtifact(), mojo.useRepositoryLayout, - mojo.stripVersion, mojo.stripType, mojo.getOutputDirectory(), artifact ); - File unpacked = new File( destDir, DependencyArtifactStubFactory.getUnpackableFileName( artifact ) ); - assertTrue( unpacked.exists() ); + public File getUnpackedFile(Artifact artifact) { + File destDir = DependencyUtil.getFormattedOutputDirectory( + mojo.isUseSubDirectoryPerScope(), + mojo.isUseSubDirectoryPerType(), + mojo.isUseSubDirectoryPerArtifact(), + mojo.useRepositoryLayout, + mojo.stripVersion, + mojo.stripType, + mojo.getOutputDirectory(), + artifact); + File unpacked = new File(destDir, DependencyArtifactStubFactory.getUnpackableFileName(artifact)); + assertTrue(unpacked.exists()); return unpacked; } public void testDontOverWriteRelease() - throws MojoExecutionException, InterruptedException, IOException, MojoFailureException - { + throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); - artifacts.add( release ); + artifacts.add(release); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteIfNewer = false; mojo.execute(); - assertUnpacked( release, false ); + assertUnpacked(release, false); } public void testOverWriteRelease() - throws MojoExecutionException, InterruptedException, IOException, MojoFailureException - { + throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); - artifacts.add( release ); + artifacts.add(release); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = true; mojo.overWriteIfNewer = false; mojo.execute(); - assertUnpacked( release, true ); + assertUnpacked(release, true); } public void testDontOverWriteSnap() - throws MojoExecutionException, InterruptedException, IOException, MojoFailureException - { + throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact snap = stubFactory.getSnapshotArtifact(); - assertTrue( snap.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(snap.getFile().setLastModified(System.currentTimeMillis() - 2000)); - artifacts.add( snap ); + artifacts.add(snap); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = false; mojo.overWriteSnapshots = false; @@ -155,21 +146,20 @@ public void testDontOverWriteSnap() mojo.execute(); - assertUnpacked( snap, false ); + assertUnpacked(snap, false); } public void testOverWriteSnap() - throws MojoExecutionException, InterruptedException, IOException, MojoFailureException - { + throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact snap = stubFactory.getSnapshotArtifact(); - assertTrue( snap.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(snap.getFile().setLastModified(System.currentTimeMillis() - 2000)); - artifacts.add( snap ); + artifacts.add(snap); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = false; mojo.overWriteSnapshots = true; @@ -177,22 +167,20 @@ public void testOverWriteSnap() mojo.execute(); - assertUnpacked( snap, true ); - + assertUnpacked(snap, true); } public void testOverWriteIfNewer() - throws MojoExecutionException, InterruptedException, IOException, MojoFailureException - { + throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set artifacts = new HashSet<>(); Artifact snap = stubFactory.getSnapshotArtifact(); - assertTrue( snap.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + assertTrue(snap.getFile().setLastModified(System.currentTimeMillis() - 2000)); - artifacts.add( snap ); + artifacts.add(snap); - mojo.getProject().setArtifacts( artifacts ); - mojo.getProject().setDependencyArtifacts( artifacts ); + mojo.getProject().setArtifacts(artifacts); + mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = false; mojo.overWriteSnapshots = false; @@ -200,57 +188,53 @@ public void testOverWriteIfNewer() mojo.execute(); - File unpackedFile = getUnpackedFile( snap ); + File unpackedFile = getUnpackedFile(snap); // round down to the last second long time = System.currentTimeMillis(); - time = time - ( time % 1000 ); + time = time - (time % 1000); // set source to be newer and dest to be a known value. - assertTrue( snap.getFile().setLastModified( time + 3000 ) ); - assertTrue( unpackedFile.setLastModified( time ) ); + assertTrue(snap.getFile().setLastModified(time + 3000)); + assertTrue(unpackedFile.setLastModified(time)); // wait at least a second for filesystems that only record to the // nearest second. - Thread.sleep( 1000 ); + Thread.sleep(1000); - assertEquals( time, unpackedFile.lastModified() ); + assertEquals(time, unpackedFile.lastModified()); mojo.execute(); System.gc(); // make sure it didn't overwrite - assertEquals( time, unpackedFile.lastModified() ); + assertEquals(time, unpackedFile.lastModified()); mojo.overWriteIfNewer = true; mojo.execute(); - assertTrue( time != unpackedFile.lastModified() ); + assertTrue(time != unpackedFile.lastModified()); System.gc(); } - public void assertUnpacked( Artifact artifact, boolean overWrite ) - throws InterruptedException, MojoExecutionException, MojoFailureException - { - File unpackedFile = getUnpackedFile( artifact ); + public void assertUnpacked(Artifact artifact, boolean overWrite) + throws InterruptedException, MojoExecutionException, MojoFailureException { + File unpackedFile = getUnpackedFile(artifact); - Thread.sleep( 100 ); + Thread.sleep(100); // round down to the last second long time = System.currentTimeMillis(); - time = time - ( time % 1000 ); - assertTrue( unpackedFile.setLastModified( time ) ); + time = time - (time % 1000); + assertTrue(unpackedFile.setLastModified(time)); // wait at least a second for filesystems that only record to the // nearest second. - Thread.sleep( 1000 ); + Thread.sleep(1000); - assertEquals( time, unpackedFile.lastModified() ); + assertEquals(time, unpackedFile.lastModified()); mojo.execute(); - if ( overWrite ) - { - assertTrue( time != unpackedFile.lastModified() ); - } - else - { - assertEquals( time, unpackedFile.lastModified() ); + if (overWrite) { + assertTrue(time != unpackedFile.lastModified()); + } else { + assertEquals(time, unpackedFile.lastModified()); } } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilterTest.java b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilterTest.java index c6de09b37..699a2c151 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilterTest.java +++ b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; + +import static java.util.Collections.singleton; +import static java.util.Collections.singletonList; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.util.HashSet; +import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.stubs.ArtifactStub; @@ -28,24 +37,9 @@ import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.mockito.ArgumentCaptor; -import java.util.HashSet; -import java.util.Set; - -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class ExcludeReactorProjectsArtifactFilterTest - extends AbstractDependencyMojoTestCase -{ +public class ExcludeReactorProjectsArtifactFilterTest extends AbstractDependencyMojoTestCase { - public void testFilter() - throws ArtifactFilterException - { + public void testFilter() throws ArtifactFilterException { Artifact artifact1 = new ArtifactStub(); artifact1.setGroupId("org.apache.maven.plugins"); artifact1.setArtifactId("maven-dependency-plugin-dummy"); @@ -57,27 +51,25 @@ public void testFilter() artifact2.setVersion("1.0"); Set artifacts = new HashSet<>(); - artifacts.add( artifact1 ); - artifacts.add( artifact2 ); + artifacts.add(artifact1); + artifacts.add(artifact2); MavenProject project = new MavenProjectStub(); project.setArtifact(artifact1); - Log log = mock( Log.class ); - when( log.isDebugEnabled() ).thenReturn( false ); + Log log = mock(Log.class); + when(log.isDebugEnabled()).thenReturn(false); - ExcludeReactorProjectsArtifactFilter filter = new ExcludeReactorProjectsArtifactFilter( - singletonList( project ), log ); + ExcludeReactorProjectsArtifactFilter filter = + new ExcludeReactorProjectsArtifactFilter(singletonList(project), log); - Set result = filter.filter( artifacts ); + Set result = filter.filter(artifacts); - assertEquals( 1, result.size() ); - verify( log, never() ).debug( any( String.class ) ); + assertEquals(1, result.size()); + verify(log, never()).debug(any(String.class)); } - public void testFilterWithLogging() - throws ArtifactFilterException - { + public void testFilterWithLogging() throws ArtifactFilterException { Artifact artifact = new ArtifactStub(); artifact.setGroupId("org.apache.maven.plugins"); artifact.setArtifactId("maven-dependency-plugin-dummy"); @@ -86,16 +78,16 @@ public void testFilterWithLogging() MavenProject project = new MavenProjectStub(); project.setArtifact(artifact); - Log log = mock( Log.class ); - when( log.isDebugEnabled() ).thenReturn( true ); + Log log = mock(Log.class); + when(log.isDebugEnabled()).thenReturn(true); - ExcludeReactorProjectsArtifactFilter filter = new ExcludeReactorProjectsArtifactFilter( - singletonList( project ), log ); + ExcludeReactorProjectsArtifactFilter filter = + new ExcludeReactorProjectsArtifactFilter(singletonList(project), log); - filter.filter( singleton( artifact ) ); + filter.filter(singleton(artifact)); - ArgumentCaptor captor = ArgumentCaptor.forClass( String.class ); - verify( log ).debug( captor.capture() ); - assertTrue( captor.getValue().contains( "Skipped artifact" ) ); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); + verify(log).debug(captor.capture()); + assertTrue(captor.getValue().contains("Skipped artifact")); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilterTest.java b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilterTest.java index 9a23afd55..e4f0e65d6 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilterTest.java +++ b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,7 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; +import static java.util.Collections.singletonList; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.logging.Log; @@ -29,20 +36,8 @@ import org.apache.maven.shared.artifact.filter.resolve.Node; import org.mockito.ArgumentCaptor; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import static java.util.Collections.singletonList; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class ExcludeReactorProjectsDependencyFilterTest extends AbstractDependencyMojoTestCase -{ - public void testReject() - { +public class ExcludeReactorProjectsDependencyFilterTest extends AbstractDependencyMojoTestCase { + public void testReject() { final Artifact artifact1 = new ArtifactStub(); artifact1.setGroupId("org.apache.maven.plugins"); artifact1.setArtifactId("maven-dependency-plugin-dummy"); @@ -54,34 +49,33 @@ public void testReject() artifact2.setVersion("1.0"); Set artifacts = new HashSet<>(); - artifacts.add( artifact1 ); - artifacts.add( artifact2 ); + artifacts.add(artifact1); + artifacts.add(artifact2); MavenProject project = new MavenProjectStub(); project.setArtifact(artifact1); - Log log = mock( Log.class ); - when( log.isDebugEnabled() ).thenReturn( false ); + Log log = mock(Log.class); + when(log.isDebugEnabled()).thenReturn(false); - ExcludeReactorProjectsDependencyFilter filter = new ExcludeReactorProjectsDependencyFilter( - singletonList( project ), log ); + ExcludeReactorProjectsDependencyFilter filter = + new ExcludeReactorProjectsDependencyFilter(singletonList(project), log); Node node = new Node() { @Override public Dependency getDependency() { final Dependency result = new Dependency(); - result.setGroupId( artifact1.getGroupId() ); - result.setArtifactId( artifact1.getArtifactId() ); - result.setVersion( artifact1.getVersion() ); + result.setGroupId(artifact1.getGroupId()); + result.setArtifactId(artifact1.getArtifactId()); + result.setVersion(artifact1.getVersion()); return result; } }; - assertFalse( filter.accept( node , Collections.emptyList() ) ); + assertFalse(filter.accept(node, Collections.emptyList())); } - public void testRejectWithLogging() - { + public void testRejectWithLogging() { final Artifact artifact1 = new ArtifactStub(); artifact1.setGroupId("org.apache.maven.plugins"); artifact1.setArtifactId("maven-dependency-plugin-dummy"); @@ -93,38 +87,37 @@ public void testRejectWithLogging() artifact2.setVersion("1.0"); Set artifacts = new HashSet<>(); - artifacts.add( artifact1 ); - artifacts.add( artifact2 ); + artifacts.add(artifact1); + artifacts.add(artifact2); MavenProject project = new MavenProjectStub(); project.setArtifact(artifact1); - Log log = mock( Log.class ); - when( log.isDebugEnabled() ).thenReturn( true ); + Log log = mock(Log.class); + when(log.isDebugEnabled()).thenReturn(true); - ExcludeReactorProjectsDependencyFilter filter = new ExcludeReactorProjectsDependencyFilter( - singletonList( project ), log ); + ExcludeReactorProjectsDependencyFilter filter = + new ExcludeReactorProjectsDependencyFilter(singletonList(project), log); Node node = new Node() { @Override public Dependency getDependency() { final Dependency result = new Dependency(); - result.setGroupId( artifact1.getGroupId() ); - result.setArtifactId( artifact1.getArtifactId() ); - result.setVersion( artifact1.getVersion() ); + result.setGroupId(artifact1.getGroupId()); + result.setArtifactId(artifact1.getArtifactId()); + result.setVersion(artifact1.getVersion()); return result; } }; - filter.accept( node , Collections.emptyList() ); + filter.accept(node, Collections.emptyList()); - ArgumentCaptor captor = ArgumentCaptor.forClass( String.class ); - verify( log ).debug( captor.capture() ); - assertTrue( captor.getValue().contains( "Skipped dependency" ) ); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); + verify(log).debug(captor.capture()); + assertTrue(captor.getValue().contains("Skipped dependency")); } - public void testAccept() - { + public void testAccept() { final Artifact artifact1 = new ArtifactStub(); artifact1.setGroupId("org.apache.maven.plugins"); artifact1.setArtifactId("maven-dependency-plugin-dummy"); @@ -136,29 +129,29 @@ public void testAccept() artifact2.setVersion("1.0"); Set artifacts = new HashSet<>(); - artifacts.add( artifact1 ); - artifacts.add( artifact2 ); + artifacts.add(artifact1); + artifacts.add(artifact2); MavenProject project = new MavenProjectStub(); project.setArtifact(artifact1); - Log log = mock( Log.class ); - when( log.isDebugEnabled() ).thenReturn( false ); + Log log = mock(Log.class); + when(log.isDebugEnabled()).thenReturn(false); - ExcludeReactorProjectsDependencyFilter filter = new ExcludeReactorProjectsDependencyFilter( - singletonList( project ), log ); + ExcludeReactorProjectsDependencyFilter filter = + new ExcludeReactorProjectsDependencyFilter(singletonList(project), log); Node node = new Node() { @Override public Dependency getDependency() { final Dependency result = new Dependency(); - result.setGroupId( "something-else" ); - result.setArtifactId( artifact1.getArtifactId() ); - result.setVersion( artifact1.getVersion() ); + result.setGroupId("something-else"); + result.setArtifactId(artifact1.getArtifactId()); + result.setVersion(artifact1.getVersion()); return result; } }; - assertTrue( filter.accept( node , Collections.emptyList() ) ); + assertTrue(filter.accept(node, Collections.emptyList())); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojoTest.java b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojoTest.java index 0bc892f6f..3685035e5 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojoTest.java @@ -1,120 +1,106 @@ -package org.apache.maven.plugins.dependency.resolvers; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; -import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; - -public class ResolveDependenciesMojoTest - extends AbstractDependencyMojoTestCase -{ - protected void setUp() - throws Exception - { - // required for mojo lookups to work - super.setUp( "dss", true ); - } - - public void testDependencyStatusLog() - throws IOException - { - Set artifacts = this.stubFactory.getMixedArtifacts(); - doTestDependencyStatusLog( artifacts ); - } - - public void testDependencyStatusLogNullFiles() - throws IOException - { - this.stubFactory.setCreateFiles( false ); - Set artifacts = this.stubFactory.getMixedArtifacts(); - doTestDependencyStatusLog( artifacts ); - } - - public void testDependencyStatusEmptySet() - { - doTestDependencyStatusLog( new HashSet() ); - } - public void testOptionalDependencyFormatting() throws IOException - { - Set set = new HashSet<>(); - Artifact artifact = stubFactory.createArtifact("g", "a", VersionRange.createFromVersion( "1.0"), - "test", "jar", null, true); - set.add(artifact); - doTestDependencyStatusLog( set ); - ResolveDependenciesMojo mojo = newMojo( new DependencyStatusSets() ); - mojo.results.setResolvedDependencies( set ); - String output = mojo.getOutput( false, true, false ); - assertTrue( output.contains( "g:a:jar:1.0:test (optional)" + System.lineSeparator() ) ); - - } - - public void doTestDependencyStatusLog( Set artifacts ) - { - // TODO: implement logger to check correct output - // this test is just looking for unexpected exceptions. - - ResolveDependenciesMojo mojo = newMojo( new DependencyStatusSets() ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( artifacts, null, null ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( null, artifacts, null ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( null, null, artifacts ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( artifacts, artifacts, null ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( null, artifacts, artifacts ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( artifacts, null, artifacts ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - - mojo = newMojo( new DependencyStatusSets( artifacts, artifacts, artifacts ) ); - mojo.getOutput( false, true, false ); - mojo.getOutput( true, true, false ); - mojo.getOutput( false, false, false ); - mojo.getOutput( true, false, false ); - } - - private ResolveDependenciesMojo newMojo( final DependencyStatusSets dss ) - { - ResolveDependenciesMojo mojo = new ResolveDependenciesMojo(); - mojo.results = dss; - return mojo; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.dependency.resolvers; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; +import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; + +public class ResolveDependenciesMojoTest extends AbstractDependencyMojoTestCase { + protected void setUp() throws Exception { + // required for mojo lookups to work + super.setUp("dss", true); + } + + public void testDependencyStatusLog() throws IOException { + Set artifacts = this.stubFactory.getMixedArtifacts(); + doTestDependencyStatusLog(artifacts); + } + + public void testDependencyStatusLogNullFiles() throws IOException { + this.stubFactory.setCreateFiles(false); + Set artifacts = this.stubFactory.getMixedArtifacts(); + doTestDependencyStatusLog(artifacts); + } + + public void testDependencyStatusEmptySet() { + doTestDependencyStatusLog(new HashSet()); + } + + public void testOptionalDependencyFormatting() throws IOException { + Set set = new HashSet<>(); + Artifact artifact = + stubFactory.createArtifact("g", "a", VersionRange.createFromVersion("1.0"), "test", "jar", null, true); + set.add(artifact); + doTestDependencyStatusLog(set); + ResolveDependenciesMojo mojo = newMojo(new DependencyStatusSets()); + mojo.results.setResolvedDependencies(set); + String output = mojo.getOutput(false, true, false); + assertTrue(output.contains("g:a:jar:1.0:test (optional)" + System.lineSeparator())); + } + + public void doTestDependencyStatusLog(Set artifacts) { + // TODO: implement logger to check correct output + // this test is just looking for unexpected exceptions. + + ResolveDependenciesMojo mojo = newMojo(new DependencyStatusSets()); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(artifacts, null, null)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(null, artifacts, null)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(null, null, artifacts)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(artifacts, artifacts, null)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(null, artifacts, artifacts)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(artifacts, null, artifacts)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + + mojo = newMojo(new DependencyStatusSets(artifacts, artifacts, artifacts)); + mojo.getOutput(false, true, false); + mojo.getOutput(true, true, false); + mojo.getOutput(false, false, false); + mojo.getOutput(true, false, false); + } + + private ResolveDependenciesMojo newMojo(final DependencyStatusSets dss) { + ResolveDependenciesMojo mojo = new ResolveDependenciesMojo(); + mojo.results = dss; + return mojo; + } +} diff --git a/src/test/java/org/apache/maven/plugins/dependency/resolvers/TestResolveMojo.java b/src/test/java/org/apache/maven/plugins/dependency/resolvers/TestResolveMojo.java index e847f90bb..2d38335f9 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/resolvers/TestResolveMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/resolvers/TestResolveMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.resolvers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,70 +16,62 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.resolvers; import java.io.File; import java.util.Set; - import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.testing.SilentLog; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; import org.apache.maven.plugins.dependency.utils.DependencyStatusSets; -import org.apache.maven.plugin.testing.SilentLog; import org.apache.maven.project.MavenProject; -public class TestResolveMojo - extends AbstractDependencyMojoTestCase -{ +public class TestResolveMojo extends AbstractDependencyMojoTestCase { - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "markers", false ); + super.setUp("markers", false); } /** * tests the proper discovery and configuration of the mojo - * + * * @throws Exception in case of errors. */ - public void testresolveTestEnvironment() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/resolve-test/plugin-config.xml" ); - ResolveDependenciesMojo mojo = (ResolveDependenciesMojo) lookupMojo( "resolve", testPom ); + public void testresolveTestEnvironment() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/resolve-test/plugin-config.xml"); + ResolveDependenciesMojo mojo = (ResolveDependenciesMojo) lookupMojo("resolve", testPom); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - mojo.setSilent( true ); + mojo.setSilent(true); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); mojo.execute(); DependencyStatusSets results = mojo.getResults(); - assertNotNull( results ); - assertEquals( artifacts.size(), results.getResolvedDependencies().size() ); + assertNotNull(results); + assertEquals(artifacts.size(), results.getResolvedDependencies().size()); - setVariableValueToObject( mojo, "excludeTransitive", Boolean.TRUE ); + setVariableValueToObject(mojo, "excludeTransitive", Boolean.TRUE); mojo.execute(); results = mojo.getResults(); - assertNotNull( results ); - assertEquals( directArtifacts.size(), results.getResolvedDependencies().size() ); + assertNotNull(results); + assertEquals(directArtifacts.size(), results.getResolvedDependencies().size()); } - public void testSilent() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/resolve-test/plugin-config.xml" ); - ResolveDependenciesMojo mojo = (ResolveDependenciesMojo) lookupMojo( "resolve", testPom ); - mojo.setSilent( false ); + public void testSilent() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/resolve-test/plugin-config.xml"); + ResolveDependenciesMojo mojo = (ResolveDependenciesMojo) lookupMojo("resolve", testPom); + mojo.setSilent(false); - assertFalse( mojo.getLog() instanceof SilentLog ); + assertFalse(mojo.getLog() instanceof SilentLog); } // TODO: Test skipping artifacts. -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/DependencyArtifactStubFactory.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/DependencyArtifactStubFactory.java index 2d7527f8e..7c49e44a3 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/DependencyArtifactStubFactory.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/DependencyArtifactStubFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.testUtils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,22 +7,22 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.testUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.versioning.VersionRange; @@ -36,15 +34,12 @@ import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; import org.codehaus.plexus.archiver.war.WarArchiver; -public class DependencyArtifactStubFactory - extends ArtifactStubFactory -{ +public class DependencyArtifactStubFactory extends ArtifactStubFactory { private boolean flattenedPath = true; private ArchiverManager archiverManager; - public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles, boolean flattenedPath ) - { - this( theWorkingDir, theCreateFiles ); + public DependencyArtifactStubFactory(File theWorkingDir, boolean theCreateFiles, boolean flattenedPath) { + this(theWorkingDir, theCreateFiles); this.flattenedPath = flattenedPath; } @@ -52,63 +47,61 @@ public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles * @param theWorkingDir {@link File} * @param theCreateFiles true/false. */ - public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles ) - { - super( theWorkingDir, theCreateFiles ); + public DependencyArtifactStubFactory(File theWorkingDir, boolean theCreateFiles) { + super(theWorkingDir, theCreateFiles); } - public ArtifactItem getArtifactItem( Artifact artifact ) - { - ArtifactItem item = new ArtifactItem( artifact ); + public ArtifactItem getArtifactItem(Artifact artifact) { + ArtifactItem item = new ArtifactItem(artifact); return item; } - public List getArtifactItems( Collection artifacts ) - { + public List getArtifactItems(Collection artifacts) { List list = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { - list.add( getArtifactItem( artifact ) ); + for (Artifact artifact : artifacts) { + list.add(getArtifactItem(artifact)); } return list; } @Override - public Artifact createArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, - String type, String classifier, boolean optional ) - throws IOException - { + public Artifact createArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String scope, + String type, + String classifier, + boolean optional) + throws IOException { File workingDir = getWorkingDir(); - if ( !flattenedPath ) - { - StringBuilder path = new StringBuilder( 128 ); + if (!flattenedPath) { + StringBuilder path = new StringBuilder(128); - path.append( groupId.replace( '.', '/' ) ).append( '/' ); + path.append(groupId.replace('.', '/')).append('/'); - path.append( artifactId ).append( '/' ); + path.append(artifactId).append('/'); - path.append( ArtifactUtils.toSnapshotVersion( versionRange.getRecommendedVersion().toString() ) ); + path.append(ArtifactUtils.toSnapshotVersion( + versionRange.getRecommendedVersion().toString())); // don't use flatten directories, won't happen at runtime - setWorkingDir( new File( workingDir, path.toString() ) ); + setWorkingDir(new File(workingDir, path.toString())); } - Artifact artifact = - super.createArtifact( groupId, artifactId, versionRange, scope, type, classifier, optional ); + Artifact artifact = super.createArtifact(groupId, artifactId, versionRange, scope, type, classifier, optional); - setWorkingDir( workingDir ); + setWorkingDir(workingDir); return artifact; } - @Override - public void setUnpackableFile( ArchiverManager archiverManager ) - { + public void setUnpackableFile(ArchiverManager archiverManager) { // it is needed in createUnpackableFile method this.archiverManager = archiverManager; - super.setUnpackableFile( archiverManager ); + super.setUnpackableFile(archiverManager); } /** @@ -117,20 +110,18 @@ public void setUnpackableFile( ArchiverManager archiverManager ) * Newer version of Archiver use SLF4J instead of Plexus logger. */ @Override - public void createUnpackableFile( Artifact artifact, File destFile ) - throws NoSuchArchiverException, ArchiverException, IOException - { - Archiver archiver = archiverManager.getArchiver( destFile ); + public void createUnpackableFile(Artifact artifact, File destFile) + throws NoSuchArchiverException, ArchiverException, IOException { + Archiver archiver = archiverManager.getArchiver(destFile); - archiver.setDestFile( destFile ); - archiver.addFile( getSrcFile(), getUnpackableFileName( artifact ) ); + archiver.setDestFile(destFile); + archiver.addFile(getSrcFile(), getUnpackableFileName(artifact)); - if ( archiver instanceof WarArchiver ) - { + if (archiver instanceof WarArchiver) { WarArchiver war = (WarArchiver) archiver; // the use of this is counter-intuitive: // http://jira.codehaus.org/browse/PLX-286 - war.setIgnoreWebxml( false ); + war.setIgnoreWebxml(false); } archiver.createArchive(); } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyProjectStub.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyProjectStub.java index f8127150b..a3a26f24e 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyProjectStub.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,15 +7,16 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; import java.io.IOException; @@ -27,7 +26,6 @@ import java.util.Map; import java.util.Properties; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.DependencyResolutionRequiredException; @@ -67,9 +65,7 @@ /** * very simple stub of maven project, going to take a lot of work to make it useful as a stub though */ -public class DependencyProjectStub - extends MavenProject -{ +public class DependencyProjectStub extends MavenProject { private String groupId; private String artifactId; @@ -148,860 +144,618 @@ public class DependencyProjectStub private Properties properties; - public DependencyProjectStub() - { - super( (Model) null ); + public DependencyProjectStub() { + super((Model) null); } // kinda dangerous... - public DependencyProjectStub( Model model ) - { + public DependencyProjectStub(Model model) { // super(model); - super( (Model) null ); + super((Model) null); } // kinda dangerous... - public DependencyProjectStub( MavenProject project ) - { + public DependencyProjectStub(MavenProject project) { // super(project); - super( (Model) null ); + super((Model) null); } - public String getModulePathAdjustment( MavenProject mavenProject ) - throws IOException - { + public String getModulePathAdjustment(MavenProject mavenProject) throws IOException { return ""; } - public Artifact getArtifact() - { - if ( artifact == null ) - { - ArtifactHandler ah = new DefaultArtifactHandlerStub( "jar", null ); + public Artifact getArtifact() { + if (artifact == null) { + ArtifactHandler ah = new DefaultArtifactHandlerStub("jar", null); - VersionRange vr = VersionRange.createFromVersion( "1.0" ); - Artifact art = - new DefaultArtifact( "group", "artifact", vr, Artifact.SCOPE_COMPILE, "jar", null, ah, false ); - setArtifact( art ); + VersionRange vr = VersionRange.createFromVersion("1.0"); + Artifact art = new DefaultArtifact("group", "artifact", vr, Artifact.SCOPE_COMPILE, "jar", null, ah, false); + setArtifact(art); } return artifact; } - public void setArtifact( Artifact artifact ) - { + public void setArtifact(Artifact artifact) { this.artifact = artifact; } - public Model getModel() - { + public Model getModel() { return model; } - public MavenProject getParent() - { + public MavenProject getParent() { return parent; } - public void setParent( MavenProject mavenProject ) - { + public void setParent(MavenProject mavenProject) { this.parent = mavenProject; } - public void setRemoteArtifactRepositories( List list ) - { + public void setRemoteArtifactRepositories(List list) {} - } - - public List getRemoteArtifactRepositories() - { + public List getRemoteArtifactRepositories() { return Collections.emptyList(); } - public boolean hasParent() - { - return ( parent != null ); + public boolean hasParent() { + return (parent != null); } - public File getFile() - { + public File getFile() { return file; } - public void setFile( File file ) - { + public void setFile(File file) { this.file = file; } - public File getBasedir() - { - return new File( PlexusTestCase.getBasedir() ); + public File getBasedir() { + return new File(PlexusTestCase.getBasedir()); } - public void setDependencies( List list ) - { + public void setDependencies(List list) { dependencies = list; } - public List getDependencies() - { - if ( dependencies == null ) - { + public List getDependencies() { + if (dependencies == null) { dependencies = Collections.emptyList(); } return dependencies; } - public void setDependencyManagement( DependencyManagement depMgt ) - { + public void setDependencyManagement(DependencyManagement depMgt) { this.dependencyManagement = depMgt; } - public DependencyManagement getDependencyManagement() - { - if ( dependencyManagement == null ) - { + public DependencyManagement getDependencyManagement() { + if (dependencyManagement == null) { dependencyManagement = new DependencyManagement(); } return dependencyManagement; } - public void addCompileSourceRoot( String string ) - { - if ( compileSourceRoots == null ) - { - compileSourceRoots = Collections.singletonList( string ); - } - else - { - compileSourceRoots.add( string ); + public void addCompileSourceRoot(String string) { + if (compileSourceRoots == null) { + compileSourceRoots = Collections.singletonList(string); + } else { + compileSourceRoots.add(string); } } - public void addScriptSourceRoot( String string ) - { - if ( scriptSourceRoots == null ) - { - scriptSourceRoots = Collections.singletonList( string ); - } - else - { - scriptSourceRoots.add( string ); + public void addScriptSourceRoot(String string) { + if (scriptSourceRoots == null) { + scriptSourceRoots = Collections.singletonList(string); + } else { + scriptSourceRoots.add(string); } } - public void addTestCompileSourceRoot( String string ) - { - if ( testCompileSourceRoots == null ) - { - testCompileSourceRoots = Collections.singletonList( string ); - } - else - { - testCompileSourceRoots.add( string ); + public void addTestCompileSourceRoot(String string) { + if (testCompileSourceRoots == null) { + testCompileSourceRoots = Collections.singletonList(string); + } else { + testCompileSourceRoots.add(string); } } - public List getCompileSourceRoots() - { + public List getCompileSourceRoots() { return compileSourceRoots; } - public List getScriptSourceRoots() - { + public List getScriptSourceRoots() { return scriptSourceRoots; } - public List getTestCompileSourceRoots() - { + public List getTestCompileSourceRoots() { return testCompileSourceRoots; } - public List getCompileClasspathElements() - throws DependencyResolutionRequiredException - { + public List getCompileClasspathElements() throws DependencyResolutionRequiredException { return compileSourceRoots; } - public void setCompileArtifacts( List compileArtifacts ) - { + public void setCompileArtifacts(List compileArtifacts) { this.compileArtifacts = compileArtifacts; } - public List getCompileArtifacts() - { + public List getCompileArtifacts() { return compileArtifacts; } - public List getCompileDependencies() - { + public List getCompileDependencies() { return compileDependencies; } - public List getTestClasspathElements() - throws DependencyResolutionRequiredException - { + public List getTestClasspathElements() throws DependencyResolutionRequiredException { return testClasspathElements; } - public List getTestArtifacts() - { + public List getTestArtifacts() { return testArtifacts; } - public List getTestDependencies() - { + public List getTestDependencies() { return testDependencies; } - public List getRuntimeClasspathElements() - throws DependencyResolutionRequiredException - { + public List getRuntimeClasspathElements() throws DependencyResolutionRequiredException { return runtimeClasspathElements; } - public List getRuntimeArtifacts() - { + public List getRuntimeArtifacts() { return runtimeArtifacts; } - public List getRuntimeDependencies() - { + public List getRuntimeDependencies() { return runtimeDependencies; } - public List getSystemClasspathElements() - throws DependencyResolutionRequiredException - { + public List getSystemClasspathElements() throws DependencyResolutionRequiredException { return systemClasspathElements; } - public List getSystemArtifacts() - { + public List getSystemArtifacts() { return systemArtifacts; } - public void setRuntimeClasspathElements( List runtimeClasspathElements ) - { + public void setRuntimeClasspathElements(List runtimeClasspathElements) { this.runtimeClasspathElements = runtimeClasspathElements; } - public void setAttachedArtifacts( List attachedArtifacts ) - { + public void setAttachedArtifacts(List attachedArtifacts) { this.attachedArtifacts = attachedArtifacts; } - public void setCompileSourceRoots( List compileSourceRoots ) - { + public void setCompileSourceRoots(List compileSourceRoots) { this.compileSourceRoots = compileSourceRoots; } - public void setTestCompileSourceRoots( List testCompileSourceRoots ) - { + public void setTestCompileSourceRoots(List testCompileSourceRoots) { this.testCompileSourceRoots = testCompileSourceRoots; } - public void setScriptSourceRoots( List scriptSourceRoots ) - { + public void setScriptSourceRoots(List scriptSourceRoots) { this.scriptSourceRoots = scriptSourceRoots; } - public void setCompileDependencies( List compileDependencies ) - { + public void setCompileDependencies(List compileDependencies) { this.compileDependencies = compileDependencies; } - public void setSystemDependencies( List systemDependencies ) - { + public void setSystemDependencies(List systemDependencies) { this.systemDependencies = systemDependencies; } - public void setTestClasspathElements( List testClasspathElements ) - { + public void setTestClasspathElements(List testClasspathElements) { this.testClasspathElements = testClasspathElements; } - public void setTestDependencies( List testDependencies ) - { + public void setTestDependencies(List testDependencies) { this.testDependencies = testDependencies; } - public void setSystemClasspathElements( List systemClasspathElements ) - { + public void setSystemClasspathElements(List systemClasspathElements) { this.systemClasspathElements = systemClasspathElements; } - public void setSystemArtifacts( List systemArtifacts ) - { + public void setSystemArtifacts(List systemArtifacts) { this.systemArtifacts = systemArtifacts; } - public void setTestArtifacts( List testArtifacts ) - { + public void setTestArtifacts(List testArtifacts) { this.testArtifacts = testArtifacts; } - public void setRuntimeArtifacts( List runtimeArtifacts ) - { + public void setRuntimeArtifacts(List runtimeArtifacts) { this.runtimeArtifacts = runtimeArtifacts; } - public void setRuntimeDependencies( List runtimeDependencies ) - { + public void setRuntimeDependencies(List runtimeDependencies) { this.runtimeDependencies = runtimeDependencies; } - public void setModel( Model model ) - { + public void setModel(Model model) { this.model = model; } - public List getSystemDependencies() - { + public List getSystemDependencies() { return systemDependencies; } - public void setModelVersion( String string ) - { + public void setModelVersion(String string) { this.modelVersion = string; } - public String getModelVersion() - { + public String getModelVersion() { return modelVersion; } - public String getId() - { + public String getId() { return ""; } - public void setGroupId( String string ) - { + public void setGroupId(String string) { this.groupId = string; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public void setArtifactId( String string ) - { + public void setArtifactId(String string) { this.artifactId = string; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setName( String string ) - { + public void setName(String string) { this.name = string; } - public String getName() - { + public String getName() { return name; } - public void setVersion( String string ) - { + public void setVersion(String string) { this.version = string; } - public String getVersion() - { + public String getVersion() { return version; } - public String getPackaging() - { + public String getPackaging() { return packaging; } - public void setPackaging( String string ) - { + public void setPackaging(String string) { this.packaging = string; } - public void setInceptionYear( String string ) - { + public void setInceptionYear(String string) { this.inceptionYear = string; } - public String getInceptionYear() - { + public String getInceptionYear() { return inceptionYear; } - public void setUrl( String string ) - { + public void setUrl(String string) { this.url = string; } - public String getUrl() - { + public String getUrl() { return url; } - public Prerequisites getPrerequisites() - { + public Prerequisites getPrerequisites() { return null; } - public void setIssueManagement( IssueManagement issueManagement ) - { + public void setIssueManagement(IssueManagement issueManagement) {} - } - - public CiManagement getCiManagement() - { + public CiManagement getCiManagement() { return null; } - public void setCiManagement( CiManagement ciManagement ) - { - - } + public void setCiManagement(CiManagement ciManagement) {} - public IssueManagement getIssueManagement() - { + public IssueManagement getIssueManagement() { return null; } - public void setDistributionManagement( DistributionManagement distributionManagement ) - { + public void setDistributionManagement(DistributionManagement distributionManagement) {} - } - - public DistributionManagement getDistributionManagement() - { + public DistributionManagement getDistributionManagement() { return null; } - public void setDescription( String string ) - { + public void setDescription(String string) { this.description = string; } - public String getDescription() - { + public String getDescription() { return description; } - public void setOrganization( Organization organization ) - { - - } + public void setOrganization(Organization organization) {} - public Organization getOrganization() - { + public Organization getOrganization() { return null; } - public void setScm( Scm scm ) - { + public void setScm(Scm scm) {} - } - - public Scm getScm() - { + public Scm getScm() { return null; } @Override - public void setMailingLists( List list ) - { + public void setMailingLists(List list) {} - } - - public List getMailingLists() - { + public List getMailingLists() { return Collections.emptyList(); } - public void addMailingList( MailingList mailingList ) - { - - } + public void addMailingList(MailingList mailingList) {} @Override - public void setDevelopers( List list ) - { - - } + public void setDevelopers(List list) {} - public List getDevelopers() - { + public List getDevelopers() { return Collections.emptyList(); } - public void addDeveloper( Developer developer ) - { + public void addDeveloper(Developer developer) {} - } + public void setContributors(List list) {} - public void setContributors( List list ) - { - - } - - public List getContributors() - { + public List getContributors() { return Collections.emptyList(); } - public void addContributor( Contributor contributor ) - { - - } - - public void setBuild( Build build ) - { + public void addContributor(Contributor contributor) {} - } + public void setBuild(Build build) {} - public Build getBuild() - { + public Build getBuild() { return null; } - public List getResources() - { + public List getResources() { return Collections.emptyList(); } - public List getTestResources() - { + public List getTestResources() { return Collections.emptyList(); } - public void addResource( Resource resource ) - { + public void addResource(Resource resource) {} - } + public void addTestResource(Resource resource) {} - public void addTestResource( Resource resource ) - { + public void setReporting(Reporting reporting) {} - } - - public void setReporting( Reporting reporting ) - { - - } - - public Reporting getReporting() - { + public Reporting getReporting() { return null; } - public void setLicenses( List list ) - { + public void setLicenses(List list) {} - } - - public List getLicenses() - { + public List getLicenses() { return Collections.emptyList(); } - public void addLicense( License license ) - { - - } + public void addLicense(License license) {} - public void setArtifacts( Set set ) - { + public void setArtifacts(Set set) { this.artifacts = set; } - public Set getArtifacts() - { - if ( artifacts == null ) - { + public Set getArtifacts() { + if (artifacts == null) { return Collections.emptySet(); - } - else - { + } else { return artifacts; } } - public Map getArtifactMap() - { + public Map getArtifactMap() { return Collections.emptyMap(); } - public void setPluginArtifacts( Set set ) - { - - } + public void setPluginArtifacts(Set set) {} - public Set getPluginArtifacts() - { + public Set getPluginArtifacts() { return Collections.emptySet(); } - public Map getPluginArtifactMap() - { + public Map getPluginArtifactMap() { return Collections.emptyMap(); } - public void setReportArtifacts( Set set ) - { - - } + public void setReportArtifacts(Set set) {} - public Set getReportArtifacts() - { + public Set getReportArtifacts() { return Collections.emptySet(); } - public Map getReportArtifactMap() - { + public Map getReportArtifactMap() { return Collections.emptyMap(); } - public void setExtensionArtifacts( Set set ) - { - - } + public void setExtensionArtifacts(Set set) {} - public Set getExtensionArtifacts() - { + public Set getExtensionArtifacts() { return Collections.emptySet(); } - public Map getExtensionArtifactMap() - { + public Map getExtensionArtifactMap() { return Collections.emptyMap(); } - public void setParentArtifact( Artifact artifact ) - { + public void setParentArtifact(Artifact artifact) {} - } - - public Artifact getParentArtifact() - { + public Artifact getParentArtifact() { return null; } - public List getRepositories() - { + public List getRepositories() { return Collections.emptyList(); } - public List getReportPlugins() - { + public List getReportPlugins() { return Collections.emptyList(); } - public List getBuildPlugins() - { + public List getBuildPlugins() { return Collections.emptyList(); } - public List getModules() - { - return Collections.singletonList( "" ); + public List getModules() { + return Collections.singletonList(""); } - public PluginManagement getPluginManagement() - { + public PluginManagement getPluginManagement() { return null; } - public void addPlugin( Plugin plugin ) - { - - } - - public void injectPluginManagementInfo( Plugin plugin ) - { + public void addPlugin(Plugin plugin) {} - } + public void injectPluginManagementInfo(Plugin plugin) {} - public List getCollectedProjects() - { + public List getCollectedProjects() { return collectedProjects; } - public void setCollectedProjects( List list ) - { + public void setCollectedProjects(List list) { this.collectedProjects = list; } - public void setPluginArtifactRepositories( List list ) - { + public void setPluginArtifactRepositories(List list) { this.pluginArtifactRepositories = list; } - public List getPluginArtifactRepositories() - { + public List getPluginArtifactRepositories() { return pluginArtifactRepositories; } - public ArtifactRepository getDistributionManagementArtifactRepository() - { + public ArtifactRepository getDistributionManagementArtifactRepository() { return null; } - public List getPluginRepositories() - { + public List getPluginRepositories() { return Collections.emptyList(); } - public void setActiveProfiles( List list ) - { + public void setActiveProfiles(List list) { activeProfiles = list; } - public List getActiveProfiles() - { + public List getActiveProfiles() { return activeProfiles; } - public void addAttachedArtifact( Artifact theArtifact ) - { - if ( attachedArtifacts == null ) - { - this.attachedArtifacts = Collections.singletonList( theArtifact ); - } - else - { - attachedArtifacts.add( theArtifact ); + public void addAttachedArtifact(Artifact theArtifact) { + if (attachedArtifacts == null) { + this.attachedArtifacts = Collections.singletonList(theArtifact); + } else { + attachedArtifacts.add(theArtifact); } } - public List getAttachedArtifacts() - { + public List getAttachedArtifacts() { return attachedArtifacts; } - public Xpp3Dom getGoalConfiguration( String string, String string1, String string2, String string3 ) - { + public Xpp3Dom getGoalConfiguration(String string, String string1, String string2, String string3) { return null; } - public Xpp3Dom getReportConfiguration( String string, String string1, String string2 ) - { + public Xpp3Dom getReportConfiguration(String string, String string1, String string2) { return null; } - public MavenProject getExecutionProject() - { + public MavenProject getExecutionProject() { return null; } - public void setExecutionProject( MavenProject mavenProject ) - { - - } - - public void writeModel( Writer writer ) - throws IOException - { - - } + public void setExecutionProject(MavenProject mavenProject) {} - public void writeOriginalModel( Writer writer ) - throws IOException - { + public void writeModel(Writer writer) throws IOException {} - } + public void writeOriginalModel(Writer writer) throws IOException {} - public Set getDependencyArtifacts() - { + public Set getDependencyArtifacts() { return dependencyArtifacts; } - public void setDependencyArtifacts( Set set ) - { + public void setDependencyArtifacts(Set set) { this.dependencyArtifacts = set; } - public void setReleaseArtifactRepository( ArtifactRepository artifactRepository ) - { + public void setReleaseArtifactRepository(ArtifactRepository artifactRepository) { // this.releaseArtifactRepository = artifactRepository; } - public void setSnapshotArtifactRepository( ArtifactRepository artifactRepository ) - { + public void setSnapshotArtifactRepository(ArtifactRepository artifactRepository) { // this.snapshotArtifactRepository = artifactRepository; } - public void setOriginalModel( Model model ) - { + public void setOriginalModel(Model model) { this.originalModel = model; } - public Model getOriginalModel() - { + public Model getOriginalModel() { return originalModel; } - public List getBuildExtensions() - { + public List getBuildExtensions() { return Collections.emptyList(); } @Override - public Set createArtifacts( ArtifactFactory artifactFactory, String string, ArtifactFilter artifactFilter ) - throws InvalidDependencyVersionException - { + public Set createArtifacts(ArtifactFactory artifactFactory, String string, ArtifactFilter artifactFilter) + throws InvalidDependencyVersionException { return Collections.emptySet(); } - public void addProjectReference( MavenProject mavenProject ) - { + public void addProjectReference(MavenProject mavenProject) {} - } - - public void attachArtifact( String string, String string1, File theFile ) - { - - } + public void attachArtifact(String string, String string1, File theFile) {} - public Properties getProperties() - { - if ( properties == null ) - { + public Properties getProperties() { + if (properties == null) { properties = new Properties(); } return properties; } - public List getFilters() - { - return Collections.singletonList( "" ); + public List getFilters() { + return Collections.singletonList(""); } - public Map getProjectReferences() - { + public Map getProjectReferences() { return Collections.emptyMap(); } - public boolean isExecutionRoot() - { + public boolean isExecutionRoot() { return executionRoot; } - public void setExecutionRoot( boolean b ) - { + public void setExecutionRoot(boolean b) { this.executionRoot = b; } - public String getDefaultGoal() - { + public String getDefaultGoal() { return defaultGoal; } - public Artifact replaceWithActiveArtifact( Artifact theArtifact ) - { + public Artifact replaceWithActiveArtifact(Artifact theArtifact) { return null; } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependencies2ProjectStub.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependencies2ProjectStub.java index 60cc77c5c..e4e779b58 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependencies2ProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependencies2ProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; import java.io.FileInputStream; import java.io.IOException; - import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.plugin.testing.stubs.MavenProjectStub; @@ -31,39 +29,31 @@ /** * very simple stub of maven project, going to take a lot of work to make it useful as a stub though */ -public class DuplicateDependencies2ProjectStub - extends MavenProjectStub -{ - public DuplicateDependencies2ProjectStub() - { - File pom = new File( getBasedir(), "plugin-config2.xml" ); +public class DuplicateDependencies2ProjectStub extends MavenProjectStub { + public DuplicateDependencies2ProjectStub() { + File pom = new File(getBasedir(), "plugin-config2.xml"); MavenXpp3Reader pomReader = new MavenXpp3Reader(); - try ( FileInputStream in = new FileInputStream( pom ) ) - { - Model model = pomReader.read( in ); - setModel( model ); - - setGroupId( model.getGroupId() ); - setArtifactId( model.getArtifactId() ); - setVersion( model.getVersion() ); - setName( model.getName() ); - setUrl( model.getUrl() ); - setPackaging( model.getPackaging() ); - setFile( pom ); - } - catch ( IOException | XmlPullParserException e ) - { - throw new RuntimeException( e ); - } + try (FileInputStream in = new FileInputStream(pom)) { + Model model = pomReader.read(in); + setModel(model); + setGroupId(model.getGroupId()); + setArtifactId(model.getArtifactId()); + setVersion(model.getVersion()); + setName(model.getName()); + setUrl(model.getUrl()); + setPackaging(model.getPackaging()); + setFile(pom); + } catch (IOException | XmlPullParserException e) { + throw new RuntimeException(e); + } } /** * @see org.apache.maven.plugin.testing.stubs.MavenProjectStub#getBasedir() */ - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/duplicate-dependencies" ); + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/duplicate-dependencies"); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependenciesProjectStub.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependenciesProjectStub.java index e26c30e8f..9c0c5af5a 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependenciesProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependenciesProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; import java.io.FileInputStream; import java.io.IOException; - import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.plugin.testing.stubs.MavenProjectStub; @@ -31,39 +29,31 @@ /** * very simple stub of maven project, going to take a lot of work to make it useful as a stub though */ -public class DuplicateDependenciesProjectStub - extends MavenProjectStub -{ - public DuplicateDependenciesProjectStub() - { - File pom = new File( getBasedir(), "plugin-config.xml" ); +public class DuplicateDependenciesProjectStub extends MavenProjectStub { + public DuplicateDependenciesProjectStub() { + File pom = new File(getBasedir(), "plugin-config.xml"); MavenXpp3Reader pomReader = new MavenXpp3Reader(); - try ( FileInputStream in = new FileInputStream( pom ) ) - { - Model model = pomReader.read( in ); - setModel( model ); - - setGroupId( model.getGroupId() ); - setArtifactId( model.getArtifactId() ); - setVersion( model.getVersion() ); - setName( model.getName() ); - setUrl( model.getUrl() ); - setPackaging( model.getPackaging() ); - setFile( pom ); - } - catch ( IOException | XmlPullParserException e ) - { - throw new RuntimeException( e ); + try (FileInputStream in = new FileInputStream(pom)) { + Model model = pomReader.read(in); + setModel(model); + + setGroupId(model.getGroupId()); + setArtifactId(model.getArtifactId()); + setVersion(model.getVersion()); + setName(model.getName()); + setUrl(model.getUrl()); + setPackaging(model.getPackaging()); + setFile(pom); + } catch (IOException | XmlPullParserException e) { + throw new RuntimeException(e); } - } /** * @see org.apache.maven.plugin.testing.stubs.MavenProjectStub#getBasedir() */ - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/duplicate-dependencies" ); + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/duplicate-dependencies"); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubDefaultFileMarkerHandler.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubDefaultFileMarkerHandler.java index 7ef4fb2d7..199664fab 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubDefaultFileMarkerHandler.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubDefaultFileMarkerHandler.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,32 +7,29 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.dependency.utils.markers.DefaultFileMarkerHandler; -public class StubDefaultFileMarkerHandler - extends DefaultFileMarkerHandler -{ +public class StubDefaultFileMarkerHandler extends DefaultFileMarkerHandler { - public StubDefaultFileMarkerHandler( Artifact artifact, File markerFilesDirectory ) - { - super( artifact, markerFilesDirectory ); + public StubDefaultFileMarkerHandler(Artifact artifact, File markerFilesDirectory) { + super(artifact, markerFilesDirectory); } - protected File getMarkerFile() - { - return new StubMarkerFile( this.markerFilesDirectory, this.artifact.getId().replace( ':', '-' ) + ".marker" ); + protected File getMarkerFile() { + return new StubMarkerFile( + this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + ".marker"); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubMarkerFile.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubMarkerFile.java index 02efee9de..82952245d 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubMarkerFile.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubMarkerFile.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,49 +7,42 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; import java.io.IOException; import java.net.URI; -public class StubMarkerFile - extends File -{ +public class StubMarkerFile extends File { private static final long serialVersionUID = 1L; - public StubMarkerFile( String pathname ) - { - super( pathname ); + public StubMarkerFile(String pathname) { + super(pathname); } - public StubMarkerFile( URI uri ) - { - super( uri ); + public StubMarkerFile(URI uri) { + super(uri); } - public StubMarkerFile( File parent, String child ) - { - super( parent, child ); + public StubMarkerFile(File parent, String child) { + super(parent, child); } - public StubMarkerFile( String parent, String child ) - { - super( parent, child ); + public StubMarkerFile(String parent, String child) { + super(parent, child); } - public boolean createNewFile() - throws IOException - { - throw new IOException( "Intended Error" ); + public boolean createNewFile() throws IOException { + throw new IOException("Intended Error"); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubSourcesFileMarkerHandler.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubSourcesFileMarkerHandler.java index 7d836cfd5..22ab432cc 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubSourcesFileMarkerHandler.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubSourcesFileMarkerHandler.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,43 +7,36 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.dependency.utils.markers.SourcesFileMarkerHandler; -public class StubSourcesFileMarkerHandler - extends SourcesFileMarkerHandler -{ +public class StubSourcesFileMarkerHandler extends SourcesFileMarkerHandler { - public StubSourcesFileMarkerHandler( Artifact artifact, File markerFilesDirectory, boolean resolved ) - { - super( artifact, markerFilesDirectory, resolved ); + public StubSourcesFileMarkerHandler(Artifact artifact, File markerFilesDirectory, boolean resolved) { + super(artifact, markerFilesDirectory, resolved); } - protected File getMarkerFile( boolean res ) - { + protected File getMarkerFile(boolean res) { String suffix; - if ( res ) - { + if (res) { suffix = ".resolved"; - } - else - { + } else { suffix = ".unresolved"; } - return new StubMarkerFile( this.markerFilesDirectory, this.artifact.getId().replace( ':', '-' ) + suffix ); + return new StubMarkerFile( + this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + suffix); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubUnpackFileMarkerHandler.java b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubUnpackFileMarkerHandler.java index 216a2f40a..dab1ebec8 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubUnpackFileMarkerHandler.java +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/StubUnpackFileMarkerHandler.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.testUtils.stubs; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,55 +7,47 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.testUtils.stubs; import java.io.File; - import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.codehaus.plexus.util.StringUtils; -public class StubUnpackFileMarkerHandler - extends UnpackFileMarkerHandler -{ - public StubUnpackFileMarkerHandler( ArtifactItem artifactItem, File markerFilesDirectory ) - { - super( artifactItem, markerFilesDirectory ); +public class StubUnpackFileMarkerHandler extends UnpackFileMarkerHandler { + public StubUnpackFileMarkerHandler(ArtifactItem artifactItem, File markerFilesDirectory) { + super(artifactItem, markerFilesDirectory); } - protected File getMarkerFile() - { + protected File getMarkerFile() { File markerFile; - if ( this.artifactItem == null || ( StringUtils.isEmpty( this.artifactItem.getIncludes() ) - && StringUtils.isEmpty( this.artifactItem.getExcludes() ) ) ) - { - markerFile = - new StubMarkerFile( this.markerFilesDirectory, this.artifact.getId().replace( ':', '-' ) + ".marker" ); - } - else - { + if (this.artifactItem == null + || (StringUtils.isEmpty(this.artifactItem.getIncludes()) + && StringUtils.isEmpty(this.artifactItem.getExcludes()))) { + markerFile = new StubMarkerFile( + this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + ".marker"); + } else { int includeExcludeHash = 0; - if ( StringUtils.isNotEmpty( this.artifactItem.getIncludes() ) ) - { + if (StringUtils.isNotEmpty(this.artifactItem.getIncludes())) { includeExcludeHash += this.artifactItem.getIncludes().hashCode(); } - if ( StringUtils.isNotEmpty( this.artifactItem.getExcludes() ) ) - { + if (StringUtils.isNotEmpty(this.artifactItem.getExcludes())) { includeExcludeHash += this.artifactItem.getExcludes().hashCode(); } - markerFile = new StubMarkerFile( this.markerFilesDirectory, - this.artifact.getId().replace( ':', '-' ) + includeExcludeHash ); + markerFile = new StubMarkerFile( + this.markerFilesDirectory, this.artifact.getId().replace(':', '-') + includeExcludeHash); } return markerFile; diff --git a/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo.java b/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo.java index 5a640dd4f..95d4f7da9 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; import java.io.BufferedReader; import java.io.File; @@ -25,7 +24,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; import org.apache.maven.project.MavenProject; @@ -38,25 +36,20 @@ * @version $Id$ * @since 2.0 */ -public class TestTreeMojo - extends AbstractDependencyMojoTestCase -{ +public class TestTreeMojo extends AbstractDependencyMojoTestCase { // TestCase methods ------------------------------------------------------- /* * @see org.apache.maven.plugin.testing.AbstractMojoTestCase#setUp() */ - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "tree", false ); + super.setUp("tree", false); } // tests ------------------------------------------------------------------ - public void testVoid() - { + public void testVoid() { // TODO: tests disabled during MDEP-339 work, to be reactivated } @@ -65,31 +58,29 @@ public void testVoid() * * @throws Exception in case of an error. */ - public void _testTreeTestEnvironment() - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/tree-test/plugin-config.xml" ); - TreeMojo mojo = (TreeMojo) lookupMojo( "tree", testPom ); - - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + public void _testTreeTestEnvironment() throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/tree-test/plugin-config.xml"); + TreeMojo mojo = (TreeMojo) lookupMojo("tree", testPom); + + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - project.setArtifact( this.stubFactory.createArtifact( "testGroupId", "project", "1.0" ) ); + project.setArtifact(this.stubFactory.createArtifact("testGroupId", "project", "1.0")); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); mojo.execute(); DependencyNode rootNode = mojo.getDependencyGraph(); - assertNodeEquals( "testGroupId:project:jar:1.0:compile", rootNode ); - assertEquals( 2, rootNode.getChildren().size() ); - assertChildNodeEquals( "testGroupId:snapshot:jar:2.0-SNAPSHOT:compile", rootNode, 0 ); - assertChildNodeEquals( "testGroupId:release:jar:1.0:compile", rootNode, 1 ); + assertNodeEquals("testGroupId:project:jar:1.0:compile", rootNode); + assertEquals(2, rootNode.getChildren().size()); + assertChildNodeEquals("testGroupId:snapshot:jar:2.0-SNAPSHOT:compile", rootNode, 0); + assertChildNodeEquals("testGroupId:release:jar:1.0:compile", rootNode, 1); } /** @@ -97,88 +88,79 @@ public void _testTreeTestEnvironment() * * @throws Exception in case of an error. */ - public void _testTreeDotSerializing() - throws Exception - { - List contents = runTreeMojo( "tree1.dot", "dot" ); - assertTrue( findString( contents, "digraph \"testGroupId:project:jar:1.0:compile\" {" ) ); - assertTrue( findString( contents, - "\"testGroupId:project:jar:1.0:compile\" -> \"testGroupId:snapshot:jar:2.0-SNAPSHOT:compile\"" ) ); - assertTrue( findString( contents, - "\"testGroupId:project:jar:1.0:compile\" -> \"testGroupId:release:jar:1.0:compile\"" ) ); + public void _testTreeDotSerializing() throws Exception { + List contents = runTreeMojo("tree1.dot", "dot"); + assertTrue(findString(contents, "digraph \"testGroupId:project:jar:1.0:compile\" {")); + assertTrue(findString( + contents, + "\"testGroupId:project:jar:1.0:compile\" -> \"testGroupId:snapshot:jar:2.0-SNAPSHOT:compile\"")); + assertTrue(findString( + contents, "\"testGroupId:project:jar:1.0:compile\" -> \"testGroupId:release:jar:1.0:compile\"")); } /** * Test the GraphML format serialization - * + * * @throws Exception in case of an error. */ - public void _testTreeGraphMLSerializing() - throws Exception - { - List contents = runTreeMojo( "tree1.graphml", "graphml" ); - - assertTrue( findString( contents, "" ) ); - assertTrue( findString( contents, "testGroupId:project:jar:1.0:compile" ) ); - assertTrue( findString( contents, - "testGroupId:snapshot:jar:2.0-SNAPSHOT:compile" ) ); - assertTrue( findString( contents, "testGroupId:release:jar:1.0:compile" ) ); - assertTrue( findString( contents, "" ) ); - assertTrue( findString( contents, "" ) ); + public void _testTreeGraphMLSerializing() throws Exception { + List contents = runTreeMojo("tree1.graphml", "graphml"); + + assertTrue(findString(contents, "")); + assertTrue(findString(contents, "testGroupId:project:jar:1.0:compile")); + assertTrue(findString(contents, "testGroupId:snapshot:jar:2.0-SNAPSHOT:compile")); + assertTrue(findString(contents, "testGroupId:release:jar:1.0:compile")); + assertTrue(findString(contents, "")); + assertTrue(findString(contents, "")); } /** * Test the TGF format serialization - * + * * @throws Exception in case of an error. */ - public void _testTreeTGFSerializing() - throws Exception - { - List contents = runTreeMojo( "tree1.tgf", "tgf" ); - assertTrue( findString( contents, "testGroupId:project:jar:1.0:compile" ) ); - assertTrue( findString( contents, "testGroupId:snapshot:jar:2.0-SNAPSHOT:compile" ) ); - assertTrue( findString( contents, "testGroupId:release:jar:1.0:compile" ) ); + public void _testTreeTGFSerializing() throws Exception { + List contents = runTreeMojo("tree1.tgf", "tgf"); + assertTrue(findString(contents, "testGroupId:project:jar:1.0:compile")); + assertTrue(findString(contents, "testGroupId:snapshot:jar:2.0-SNAPSHOT:compile")); + assertTrue(findString(contents, "testGroupId:release:jar:1.0:compile")); } /** * Help finding content in the given list of string - * + * * @param outputFile the outputFile. * @param format The format. * @throws Exception in case of an error. * @return list of strings in the output file */ - private List runTreeMojo( String outputFile, String format ) - throws Exception - { - File testPom = new File( getBasedir(), "target/test-classes/unit/tree-test/plugin-config.xml" ); + private List runTreeMojo(String outputFile, String format) throws Exception { + File testPom = new File(getBasedir(), "target/test-classes/unit/tree-test/plugin-config.xml"); String outputFileName = testDir.getAbsolutePath() + outputFile; - TreeMojo mojo = (TreeMojo) lookupMojo( "tree", testPom ); - setVariableValueToObject( mojo, "outputType", format ); - setVariableValueToObject( mojo, "outputFile", new File( outputFileName ) ); + TreeMojo mojo = (TreeMojo) lookupMojo("tree", testPom); + setVariableValueToObject(mojo, "outputType", format); + setVariableValueToObject(mojo, "outputFile", new File(outputFileName)); - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); + assertNotNull(mojo); + assertNotNull(mojo.getProject()); MavenProject project = mojo.getProject(); - project.setArtifact( this.stubFactory.createArtifact( "testGroupId", "project", "1.0" ) ); + project.setArtifact(this.stubFactory.createArtifact("testGroupId", "project", "1.0")); Set artifacts = this.stubFactory.getScopedArtifacts(); Set directArtifacts = this.stubFactory.getReleaseAndSnapshotArtifacts(); - artifacts.addAll( directArtifacts ); + artifacts.addAll(directArtifacts); - project.setArtifacts( artifacts ); - project.setDependencyArtifacts( directArtifacts ); + project.setArtifacts(artifacts); + project.setDependencyArtifacts(directArtifacts); mojo.execute(); - BufferedReader fp1 = new BufferedReader( new FileReader( outputFileName ) ); + BufferedReader fp1 = new BufferedReader(new FileReader(outputFileName)); List contents = new ArrayList<>(); String line; - while ( ( line = fp1.readLine() ) != null ) - { - contents.add( line ); + while ((line = fp1.readLine()) != null) { + contents.add(line); } fp1.close(); @@ -187,16 +169,13 @@ private List runTreeMojo( String outputFile, String format ) /** * Help finding content in the given list of string - * + * * @param contents The contents. * @param str The content which should be checked for. */ - private boolean findString( List contents, String str ) - { - for ( String line : contents ) - { - if ( line.contains( str ) ) - { + private boolean findString(List contents, String str) { + for (String line : contents) { + if (line.contains(str)) { // if match then return here return true; } @@ -208,29 +187,31 @@ private boolean findString( List contents, String str ) // private methods -------------------------------------------------------- - private void assertChildNodeEquals( String expectedNode, DependencyNode actualParentNode, int actualChildIndex ) - { - DependencyNode actualNode = actualParentNode.getChildren().get( actualChildIndex ); + private void assertChildNodeEquals(String expectedNode, DependencyNode actualParentNode, int actualChildIndex) { + DependencyNode actualNode = actualParentNode.getChildren().get(actualChildIndex); - assertNodeEquals( expectedNode, actualNode ); + assertNodeEquals(expectedNode, actualNode); } - private void assertNodeEquals( String expectedNode, DependencyNode actualNode ) - { - String[] tokens = expectedNode.split( ":" ); + private void assertNodeEquals(String expectedNode, DependencyNode actualNode) { + String[] tokens = expectedNode.split(":"); - assertNodeEquals( tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], actualNode ); + assertNodeEquals(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], actualNode); } - private void assertNodeEquals( String expectedGroupId, String expectedArtifactId, String expectedType, - String expectedVersion, String expectedScope, DependencyNode actualNode ) - { + private void assertNodeEquals( + String expectedGroupId, + String expectedArtifactId, + String expectedType, + String expectedVersion, + String expectedScope, + DependencyNode actualNode) { Artifact actualArtifact = actualNode.getArtifact(); - assertEquals( "group id", expectedGroupId, actualArtifact.getGroupId() ); - assertEquals( "artifact id", expectedArtifactId, actualArtifact.getArtifactId() ); - assertEquals( "type", expectedType, actualArtifact.getType() ); - assertEquals( "version", expectedVersion, actualArtifact.getVersion() ); - assertEquals( "scope", expectedScope, actualArtifact.getScope() ); + assertEquals("group id", expectedGroupId, actualArtifact.getGroupId()); + assertEquals("artifact id", expectedArtifactId, actualArtifact.getArtifactId()); + assertEquals("type", expectedType, actualArtifact.getType()); + assertEquals("version", expectedVersion, actualArtifact.getVersion()); + assertEquals("scope", expectedScope, actualArtifact.getScope()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo_ContainsVersion.java b/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo_ContainsVersion.java index 015d7d776..ff90ca33a 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo_ContainsVersion.java +++ b/src/test/java/org/apache/maven/plugins/dependency/tree/TestTreeMojo_ContainsVersion.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.tree; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,35 +16,33 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.tree; + +import static org.apache.maven.plugins.dependency.tree.TreeMojo.containsVersion; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.util.Collections; import junit.framework.TestCase; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.Restriction; import org.apache.maven.artifact.versioning.VersionRange; -import java.util.Collections; - -import static org.apache.maven.plugins.dependency.tree.TreeMojo.containsVersion; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - /** * Tests TreeMojo.containsVersion. */ -public class TestTreeMojo_ContainsVersion extends TestCase -{ - private VersionRange range = mock( VersionRange.class ); +public class TestTreeMojo_ContainsVersion extends TestCase { + private VersionRange range = mock(VersionRange.class); - private ArtifactVersion version = mock( ArtifactVersion.class ); + private ArtifactVersion version = mock(ArtifactVersion.class); - public void testWhenRecommendedVersionIsNullAndNoRestrictions() - { - when( range.getRecommendedVersion() ).thenReturn( null ); - when( range.getRestrictions() ).thenReturn( Collections.emptyList() ); + public void testWhenRecommendedVersionIsNullAndNoRestrictions() { + when(range.getRecommendedVersion()).thenReturn(null); + when(range.getRestrictions()).thenReturn(Collections.emptyList()); - @SuppressWarnings( "deprecation" ) - boolean doesItContain = containsVersion( range, version ); + @SuppressWarnings("deprecation") + boolean doesItContain = containsVersion(range, version); - assertFalse( doesItContain ); + assertFalse(doesItContain); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyStatusSets.java b/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyStatusSets.java index 2a8750188..7da3810f7 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyStatusSets.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyStatusSets.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,22 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; -public class TestDependencyStatusSets - extends AbstractDependencyMojoTestCase -{ +public class TestDependencyStatusSets extends AbstractDependencyMojoTestCase { - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work - super.setUp( "dss", true ); + super.setUp("dss", true); } - public void testDependencyStatusSettersGetters() - { + public void testDependencyStatusSettersGetters() { /* * DependencyStatusSets dss = new DependencyStatusSets(); Set set = new HashSet(); dss.setResolvedDependencies( * set ); assertSame( set, dss.getResolvedDependencies() ); set = new HashSet(); dss.setUnResolvedDependencies( @@ -44,8 +38,7 @@ public void testDependencyStatusSettersGetters() */ } - public void testDependencyStatusConstructor() - { + public void testDependencyStatusConstructor() { /* * Set r = new HashSet(); Set u = new HashSet(); Set s = new HashSet(); DependencyStatusSets dss = new * DependencyStatusSets( r, u, s ); assertSame( r, dss.getResolvedDependencies() ); assertSame( u, diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyUtil.java b/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyUtil.java index c9cb4c19f..8302b70f5 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyUtil.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/TestDependencyUtil.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,23 +7,22 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; - import junit.framework.TestCase; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; @@ -38,9 +35,7 @@ /** * @author brianf */ -public class TestDependencyUtil - extends TestCase -{ +public class TestDependencyUtil extends TestCase { List artifacts = new ArrayList<>(); Log log = new SilentLog(); @@ -56,303 +51,290 @@ public class TestDependencyUtil Artifact sources; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - ArtifactHandler ah = new DefaultArtifactHandlerStub( "jar", null ); - VersionRange vr = VersionRange.createFromVersion( "1.1" ); - release = new DefaultArtifact( "test", "one", vr, Artifact.SCOPE_COMPILE, "jar", "sources", ah, false ); - artifacts.add( release ); + ArtifactHandler ah = new DefaultArtifactHandlerStub("jar", null); + VersionRange vr = VersionRange.createFromVersion("1.1"); + release = new DefaultArtifact("test", "one", vr, Artifact.SCOPE_COMPILE, "jar", "sources", ah, false); + artifacts.add(release); - ah = new DefaultArtifactHandlerStub( "war", null ); - vr = VersionRange.createFromVersion( "1.1-SNAPSHOT" ); - snap = new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "war", null, ah, false ); - artifacts.add( snap ); + ah = new DefaultArtifactHandlerStub("war", null); + vr = VersionRange.createFromVersion("1.1-SNAPSHOT"); + snap = new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "war", null, ah, false); + artifacts.add(snap); - ah = new DefaultArtifactHandlerStub( "war", null ); - vr = VersionRange.createFromVersion( "1.1-SNAPSHOT" ); - snapResolvedVersion = - new DefaultArtifact( "test", "three", vr, Artifact.SCOPE_PROVIDED, "war", null, ah, false ); - snapResolvedVersion.setResolvedVersion( "1.1-20121003.035531-117" ); - artifacts.add( snapResolvedVersion ); + ah = new DefaultArtifactHandlerStub("war", null); + vr = VersionRange.createFromVersion("1.1-SNAPSHOT"); + snapResolvedVersion = new DefaultArtifact("test", "three", vr, Artifact.SCOPE_PROVIDED, "war", null, ah, false); + snapResolvedVersion.setResolvedVersion("1.1-20121003.035531-117"); + artifacts.add(snapResolvedVersion); - ah = new DefaultArtifactHandlerStub( "war", null ); - vr = VersionRange.createFromVersion( "1.1-SNAPSHOT" ); - sources = new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "sources", "sources", ah, false ); + ah = new DefaultArtifactHandlerStub("war", null); + vr = VersionRange.createFromVersion("1.1-SNAPSHOT"); + sources = new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "sources", "sources", ah, false); // pick random output location Random a = new Random(); - outputFolder = new File( "target/copy" + a.nextLong() + "/" ); + outputFolder = new File("target/copy" + a.nextLong() + "/"); outputFolder.delete(); - assertFalse( outputFolder.exists() ); + assertFalse(outputFolder.exists()); } - public void testDirectoryName() - { - File folder = new File( "target/a" ); - final Artifact artifact = artifacts.get( 0 ); - File name = DependencyUtil.getFormattedOutputDirectory( false, false, false, false, false, false, folder, artifact ); + public void testDirectoryName() { + File folder = new File("target/a"); + final Artifact artifact = artifacts.get(0); + File name = + DependencyUtil.getFormattedOutputDirectory(false, false, false, false, false, false, folder, artifact); // object is the same. - assertEquals( folder, name ); + assertEquals(folder, name); - name = DependencyUtil.getFormattedOutputDirectory( false, false, false, true, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, false, true, false, false, folder, artifact); String expectedResult = folder.getAbsolutePath() + File.separatorChar + "test" + File.separatorChar + "one" - + File.separatorChar + "1.1"; - assertTrue( expectedResult.equalsIgnoreCase( name.getAbsolutePath() ) ); + + File.separatorChar + "1.1"; + assertTrue(expectedResult.equalsIgnoreCase(name.getAbsolutePath())); - name = DependencyUtil.getFormattedOutputDirectory( false, true, false, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, false, false, false, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "jars"; - assertTrue( expectedResult.equalsIgnoreCase( name.getAbsolutePath() ) ); + assertTrue(expectedResult.equalsIgnoreCase(name.getAbsolutePath())); - name = DependencyUtil.getFormattedOutputDirectory( true, false, false, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(true, false, false, false, false, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "compile"; - assertEquals( expectedResult, name.getAbsolutePath() ); - assertTrue( expectedResult.equalsIgnoreCase( name.getAbsolutePath() ) ); + assertEquals(expectedResult, name.getAbsolutePath()); + assertTrue(expectedResult.equalsIgnoreCase(name.getAbsolutePath())); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, false, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "one-1.1-sources-jar"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, true, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "one-sources-jar"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, false, true, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "one-1.1-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, true, true, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "one-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, false, false, folder, artifact); expectedResult = - folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-1.1-sources-jar"; - assertEquals( expectedResult, name.getAbsolutePath() ); + folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-1.1-sources-jar"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, true, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, true, false, folder, artifact); expectedResult = - folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-sources-jar"; - assertEquals( expectedResult, name.getAbsolutePath() ); + folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-sources-jar"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, false, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, false, true, folder, artifact); expectedResult = - folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-1.1-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-1.1-sources"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, true, true, folder, artifact ); - expectedResult = - folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, true, true, folder, artifact); + expectedResult = folder.getAbsolutePath() + File.separatorChar + "jars" + File.separatorChar + "one-sources"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( true, false, true, false, true, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(true, false, true, false, true, false, folder, artifact); expectedResult = - folder.getAbsolutePath() + File.separatorChar + "compile" + File.separatorChar + "one-sources-jar"; - assertEquals( expectedResult, name.getAbsolutePath() ); + folder.getAbsolutePath() + File.separatorChar + "compile" + File.separatorChar + "one-sources-jar"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( true, false, true, false, false, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(true, false, true, false, false, true, folder, artifact); expectedResult = - folder.getAbsolutePath() + File.separatorChar + "compile" + File.separatorChar + "one-1.1-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + folder.getAbsolutePath() + File.separatorChar + "compile" + File.separatorChar + "one-1.1-sources"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( true, false, true, false, true, true, folder, artifact ); - expectedResult = - folder.getAbsolutePath() + File.separatorChar + "compile" + File.separatorChar + "one-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + name = DependencyUtil.getFormattedOutputDirectory(true, false, true, false, true, true, folder, artifact); + expectedResult = folder.getAbsolutePath() + File.separatorChar + "compile" + File.separatorChar + "one-sources"; + assertEquals(expectedResult, name.getAbsolutePath()); } - public void testDirectoryName2() - { - File folder = new File( "target/a" ); - final Artifact artifact = artifacts.get( 1 ); - File name = DependencyUtil.getFormattedOutputDirectory( false, false, false, false, false, false, folder, artifact ); + public void testDirectoryName2() { + File folder = new File("target/a"); + final Artifact artifact = artifacts.get(1); + File name = + DependencyUtil.getFormattedOutputDirectory(false, false, false, false, false, false, folder, artifact); // object is the same. - assertEquals( folder, name ); + assertEquals(folder, name); - name = DependencyUtil.getFormattedOutputDirectory( false, true, false, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, false, false, false, false, folder, artifact); String expectedResult = folder.getAbsolutePath() + File.separatorChar + "wars"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, false, true, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, false, true, false, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "test" + File.separatorChar + "two" - + File.separatorChar + "1.1-SNAPSHOT"; - assertEquals( expectedResult, name.getAbsolutePath() ); + + File.separatorChar + "1.1-SNAPSHOT"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, false, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-1.1-SNAPSHOT-war"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, false, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, false, false, folder, artifact); expectedResult = - folder.getAbsolutePath() + File.separatorChar + "wars" + File.separatorChar + "two-1.1-SNAPSHOT-war"; - assertEquals( expectedResult, name.getAbsolutePath() ); + folder.getAbsolutePath() + File.separatorChar + "wars" + File.separatorChar + "two-1.1-SNAPSHOT-war"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, true, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-war"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, false, true, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-1.1-SNAPSHOT"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, true, true, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, true, false, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, true, false, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "wars" + File.separatorChar + "two-war"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, false, true, folder, artifact ); - expectedResult = folder.getAbsolutePath() + File.separatorChar + "wars" + File.separatorChar + "two-1.1-SNAPSHOT"; - assertEquals( expectedResult, name.getAbsolutePath() ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, false, true, folder, artifact); + expectedResult = + folder.getAbsolutePath() + File.separatorChar + "wars" + File.separatorChar + "two-1.1-SNAPSHOT"; + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, true, true, false, true, true, folder, artifact ); + name = DependencyUtil.getFormattedOutputDirectory(false, true, true, false, true, true, folder, artifact); expectedResult = folder.getAbsolutePath() + File.separatorChar + "wars" + File.separatorChar + "two"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); } - public void testDirectoryNameSources() - { - File folder = new File( "target/a" ); - File name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, false, folder, sources ); + public void testDirectoryNameSources() { + File folder = new File("target/a"); + File name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, true, false, folder, sources); String expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, true, true, folder, sources ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, true, true, folder, sources); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, false, folder, sources ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, false, false, folder, sources); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-1.1-SNAPSHOT-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); - name = DependencyUtil.getFormattedOutputDirectory( false, false, true, false, false, true, folder, sources ); + name = DependencyUtil.getFormattedOutputDirectory(false, false, true, false, false, true, folder, sources); expectedResult = folder.getAbsolutePath() + File.separatorChar + "two-1.1-SNAPSHOT-sources"; - assertEquals( expectedResult, name.getAbsolutePath() ); + assertEquals(expectedResult, name.getAbsolutePath()); } - public void testFileName() - { - Artifact artifact = artifacts.get( 0 ); + public void testFileName() { + Artifact artifact = artifacts.get(0); - String name = DependencyUtil.getFormattedFileName( artifact, false ); + String name = DependencyUtil.getFormattedFileName(artifact, false); String expectedResult = "one-1.1-sources.jar"; - assertEquals( expectedResult, name ); - name = DependencyUtil.getFormattedFileName( artifact, true ); + assertEquals(expectedResult, name); + name = DependencyUtil.getFormattedFileName(artifact, true); expectedResult = "one-sources.jar"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); } - public void testFileNameUseBaseVersion() - { + public void testFileNameUseBaseVersion() { Artifact artifact = snapResolvedVersion; - String name = DependencyUtil.getFormattedFileName( artifact, false, false, true ); + String name = DependencyUtil.getFormattedFileName(artifact, false, false, true); String expectedResult = "three-1.1-SNAPSHOT.war"; - assertEquals( expectedResult, name ); - name = DependencyUtil.getFormattedFileName( artifact, false, false, false ); + assertEquals(expectedResult, name); + name = DependencyUtil.getFormattedFileName(artifact, false, false, false); expectedResult = "three-1.1-20121003.035531-117.war"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); } - public void testTestJar() - { - ArtifactHandler ah = new DefaultArtifactHandlerStub( "test-jar", null ); - VersionRange vr = VersionRange.createFromVersion( "1.1-SNAPSHOT" ); + public void testTestJar() { + ArtifactHandler ah = new DefaultArtifactHandlerStub("test-jar", null); + VersionRange vr = VersionRange.createFromVersion("1.1-SNAPSHOT"); Artifact artifact = - new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "test-jar", null, ah, false ); + new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "test-jar", null, ah, false); - String name = DependencyUtil.getFormattedFileName( artifact, false ); + String name = DependencyUtil.getFormattedFileName(artifact, false); String expectedResult = "two-1.1-SNAPSHOT.jar"; - assertEquals( expectedResult, name ); - + assertEquals(expectedResult, name); } - public void testFileNameClassifier() - { - ArtifactHandler ah = new DefaultArtifactHandlerStub( "jar", "sources" ); - VersionRange vr = VersionRange.createFromVersion( "1.1-SNAPSHOT" ); + public void testFileNameClassifier() { + ArtifactHandler ah = new DefaultArtifactHandlerStub("jar", "sources"); + VersionRange vr = VersionRange.createFromVersion("1.1-SNAPSHOT"); Artifact artifact = - new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "jar", "sources", ah, false ); + new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "jar", "sources", ah, false); - String name = DependencyUtil.getFormattedFileName( artifact, false ); + String name = DependencyUtil.getFormattedFileName(artifact, false); String expectedResult = "two-1.1-SNAPSHOT-sources.jar"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); - name = DependencyUtil.getFormattedFileName( artifact, true ); + name = DependencyUtil.getFormattedFileName(artifact, true); expectedResult = "two-sources.jar"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); - name = DependencyUtil.getFormattedFileName( artifact, false, false, false, true ); + name = DependencyUtil.getFormattedFileName(artifact, false, false, false, true); expectedResult = "two-1.1-SNAPSHOT.jar"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); - ah = new DefaultArtifactHandlerStub( "war", null ); - artifact = new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false ); - name = DependencyUtil.getFormattedFileName( artifact, true ); + ah = new DefaultArtifactHandlerStub("war", null); + artifact = new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false); + name = DependencyUtil.getFormattedFileName(artifact, true); expectedResult = "two.war"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); } - public void testFileNameClassifierWithFile() - { + public void testFileNameClassifierWithFile() { // specifically testing the default operation that getFormattedFileName // returns // the actual name of the file if available unless remove version is // set. - ArtifactHandler ah = new DefaultArtifactHandlerStub( "war", "sources" ); - VersionRange vr = VersionRange.createFromVersion( "1.1-SNAPSHOT" ); + ArtifactHandler ah = new DefaultArtifactHandlerStub("war", "sources"); + VersionRange vr = VersionRange.createFromVersion("1.1-SNAPSHOT"); Artifact artifact = - new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "sources", ah, false ); - File file = new File( "/target", "test-file-name.jar" ); - artifact.setFile( file ); + new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "sources", ah, false); + File file = new File("/target", "test-file-name.jar"); + artifact.setFile(file); - String name = DependencyUtil.getFormattedFileName( artifact, false ); + String name = DependencyUtil.getFormattedFileName(artifact, false); String expectedResult = "two-1.1-SNAPSHOT-sources.war"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); - name = DependencyUtil.getFormattedFileName( artifact, false, false, false, true ); + name = DependencyUtil.getFormattedFileName(artifact, false, false, false, true); expectedResult = "two-1.1-SNAPSHOT.war"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); - name = DependencyUtil.getFormattedFileName( artifact, true ); + name = DependencyUtil.getFormattedFileName(artifact, true); expectedResult = "two-sources.war"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); - artifact = new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false ); - name = DependencyUtil.getFormattedFileName( artifact, true ); + artifact = new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false); + name = DependencyUtil.getFormattedFileName(artifact, true); expectedResult = "two.war"; - assertEquals( expectedResult, name ); + assertEquals(expectedResult, name); // test that we pickup the correct extension in the file name if set. - ah = new DefaultArtifactHandlerStub( "jar", null ); - artifact = new DefaultArtifact( "test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false ); - name = DependencyUtil.getFormattedFileName( artifact, true ); + ah = new DefaultArtifactHandlerStub("jar", null); + artifact = new DefaultArtifact("test", "two", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false); + name = DependencyUtil.getFormattedFileName(artifact, true); expectedResult = "two.jar"; - assertEquals( expectedResult, name ); - + assertEquals(expectedResult, name); } - public void testTokenizer() - { - String[] tokens = DependencyUtil.tokenizer( " alpha,bravo, charlie , delta kappa, theta" ); - String[] expected = new String[] { "alpha", "bravo", "charlie", "delta kappa", "theta" }; + public void testTokenizer() { + String[] tokens = DependencyUtil.tokenizer(" alpha,bravo, charlie , delta kappa, theta"); + String[] expected = new String[] {"alpha", "bravo", "charlie", "delta kappa", "theta"}; // easier to see in the JUnit reports - assertEquals( StringUtils.join( expected, ", " ), StringUtils.join( tokens, ", " ) ); - assertEquals( expected.length, tokens.length ); + assertEquals(StringUtils.join(expected, ", "), StringUtils.join(tokens, ", ")); + assertEquals(expected.length, tokens.length); - tokens = DependencyUtil.tokenizer( " \r\n a, \t \n \r b \t \n \r" ); - assertEquals( 2, tokens.length ); - assertEquals( "a", tokens[0] ); - assertEquals( "b", tokens[1] ); + tokens = DependencyUtil.tokenizer(" \r\n a, \t \n \r b \t \n \r"); + assertEquals(2, tokens.length); + assertEquals("a", tokens[0]); + assertEquals("b", tokens[1]); - tokens = DependencyUtil.tokenizer( null ); - assertEquals( 0, tokens.length ); + tokens = DependencyUtil.tokenizer(null); + assertEquals(0, tokens.length); - tokens = DependencyUtil.tokenizer( " " ); - assertEquals( 0, tokens.length ); + tokens = DependencyUtil.tokenizer(" "); + assertEquals(0, tokens.length); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/TestSilentLog.java b/src/test/java/org/apache/maven/plugins/dependency/utils/TestSilentLog.java index 25139c088..231419ea3 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/TestSilentLog.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/TestSilentLog.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.dependency.utils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,57 +16,53 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.dependency.utils; import junit.framework.TestCase; - import org.apache.maven.plugin.logging.Log; import org.codehaus.plexus.logging.Logger; -public class TestSilentLog - extends TestCase -{ +public class TestSilentLog extends TestCase { - public void testLog() - { + public void testLog() { Log log = new DependencySilentLog(); String text = "Text"; Throwable e = new RuntimeException(); - log.debug( text ); - log.debug( text, e ); - log.debug( e ); - log.info( text ); - log.info( text, e ); - log.info( e ); - log.warn( text ); - log.warn( text, e ); - log.warn( e ); - log.error( text ); - log.error( text, e ); - log.error( e ); + log.debug(text); + log.debug(text, e); + log.debug(e); + log.info(text); + log.info(text, e); + log.info(e); + log.warn(text); + log.warn(text, e); + log.warn(e); + log.error(text); + log.error(text, e); + log.error(e); log.isDebugEnabled(); log.isErrorEnabled(); log.isWarnEnabled(); log.isInfoEnabled(); } - public void testLogger() - { + public void testLogger() { Logger log = new DependencySilentLog(); String text = "Text"; Throwable e = new RuntimeException(); - log.debug( text ); - log.debug( text, e ); - log.error( text ); - log.error( text, e ); - log.warn( text ); - log.warn( text, e ); - log.info( text ); - log.info( text, e ); + log.debug(text); + log.debug(text, e); + log.error(text); + log.error(text, e); + log.warn(text); + log.warn(text, e); + log.info(text); + log.info(text, e); - log.fatalError( text ); - log.fatalError( text, e ); - log.getChildLogger( text ); + log.fatalError(text); + log.fatalError(text, e); + log.getChildLogger(text); log.getName(); log.getThreshold(); log.isDebugEnabled(); @@ -77,5 +71,4 @@ public void testLogger() log.isInfoEnabled(); log.isWarnEnabled(); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestDestFileFilter.java b/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestDestFileFilter.java index aacaae2eb..b3e627c34 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestDestFileFilter.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestDestFileFilter.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.filters; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,38 +7,35 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; - import junit.framework.TestCase; - import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; -import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.SilentLog; +import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; +import org.apache.maven.plugins.dependency.utils.DependencyUtil; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; /** * @author brianf */ -public class TestDestFileFilter - extends TestCase -{ +public class TestDestFileFilter extends TestCase { Set artifacts = new HashSet<>(); Log log = new SilentLog(); @@ -49,204 +44,187 @@ public class TestDestFileFilter DependencyArtifactStubFactory fact; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - outputFolder = new File( "target/markers/" ); - FileUtils.deleteDirectory( outputFolder ); - assertFalse( outputFolder.exists() ); + outputFolder = new File("target/markers/"); + FileUtils.deleteDirectory(outputFolder); + assertFalse(outputFolder.exists()); - this.fact = new DependencyArtifactStubFactory( outputFolder, false ); + this.fact = new DependencyArtifactStubFactory(outputFolder, false); artifacts = fact.getReleaseAndSnapshotArtifacts(); } - protected void tearDown() - throws IOException - { - FileUtils.deleteDirectory( outputFolder ); + protected void tearDown() throws IOException { + FileUtils.deleteDirectory(outputFolder); } - public File createFile( Artifact artifact ) - throws IOException - { - return createFile( artifact, false, false, false ); + public File createFile(Artifact artifact) throws IOException { + return createFile(artifact, false, false, false); } - public File createFile( Artifact artifact, boolean useSubDirectoryPerArtifact, boolean useSubDirectoryPerType, - boolean removeVersion ) - throws IOException - { - return createFile( artifact, useSubDirectoryPerArtifact, useSubDirectoryPerType, removeVersion, false ); + public File createFile( + Artifact artifact, + boolean useSubDirectoryPerArtifact, + boolean useSubDirectoryPerType, + boolean removeVersion) + throws IOException { + return createFile(artifact, useSubDirectoryPerArtifact, useSubDirectoryPerType, removeVersion, false); } - public File createFile( Artifact artifact, boolean useSubDirectoryPerArtifact, boolean useSubDirectoryPerType, - boolean removeVersion, boolean removeClassifier ) - throws IOException - { - File destFolder = - DependencyUtil.getFormattedOutputDirectory( false, useSubDirectoryPerType, useSubDirectoryPerArtifact, - false, false, false, outputFolder, artifact ); - File destFile = - new File( destFolder, - DependencyUtil.getFormattedFileName( artifact, removeVersion, false, false, removeClassifier ) ); + public File createFile( + Artifact artifact, + boolean useSubDirectoryPerArtifact, + boolean useSubDirectoryPerType, + boolean removeVersion, + boolean removeClassifier) + throws IOException { + File destFolder = DependencyUtil.getFormattedOutputDirectory( + false, useSubDirectoryPerType, useSubDirectoryPerArtifact, false, false, false, outputFolder, artifact); + File destFile = new File( + destFolder, + DependencyUtil.getFormattedFileName(artifact, removeVersion, false, false, removeClassifier)); destFile.getParentFile().mkdirs(); - assertTrue( destFile.createNewFile() ); + assertTrue(destFile.createNewFile()); return destFile; } - public void testDestFileRelease() - throws IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileRelease() throws IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); Artifact artifact = fact.getReleaseArtifact(); - assertTrue( filter.isArtifactIncluded( artifact ) ); - createFile( artifact ); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); + createFile(artifact); + assertFalse(filter.isArtifactIncluded(artifact)); - filter.setOverWriteReleases( true ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + filter.setOverWriteReleases(true); + assertTrue(filter.isArtifactIncluded(artifact)); } - public void testDestFileSnapshot() - throws IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileSnapshot() throws IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); Artifact artifact = fact.getSnapshotArtifact(); - assertTrue( filter.isArtifactIncluded( artifact ) ); - createFile( artifact ); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); + createFile(artifact); + assertFalse(filter.isArtifactIncluded(artifact)); - filter.setOverWriteSnapshots( true ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + filter.setOverWriteSnapshots(true); + assertTrue(filter.isArtifactIncluded(artifact)); } - public void testDestFileStripVersion() - throws IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileStripVersion() throws IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); Artifact artifact = fact.getSnapshotArtifact(); - filter.setRemoveVersion( true ); + filter.setRemoveVersion(true); - assertTrue( filter.isArtifactIncluded( artifact ) ); - createFile( artifact, false, false, true ); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); + createFile(artifact, false, false, true); + assertFalse(filter.isArtifactIncluded(artifact)); - filter.setOverWriteSnapshots( true ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + filter.setOverWriteSnapshots(true); + assertTrue(filter.isArtifactIncluded(artifact)); } - public void testDestFileStripClassifier() - throws IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileStripClassifier() throws IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); Artifact artifact = fact.getSnapshotArtifact(); - filter.setRemoveClassifier( true ); + filter.setRemoveClassifier(true); - assertTrue( filter.isArtifactIncluded( artifact ) ); - createFile( artifact, false, false, false, true ); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); + createFile(artifact, false, false, false, true); + assertFalse(filter.isArtifactIncluded(artifact)); - filter.setOverWriteSnapshots( true ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + filter.setOverWriteSnapshots(true); + assertTrue(filter.isArtifactIncluded(artifact)); } - public void testDestFileSubPerArtifact() - throws IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileSubPerArtifact() throws IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); Artifact artifact = fact.getSnapshotArtifact(); - filter.setUseSubDirectoryPerArtifact( true ); + filter.setUseSubDirectoryPerArtifact(true); - assertTrue( filter.isArtifactIncluded( artifact ) ); - createFile( artifact, true, false, false ); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); + createFile(artifact, true, false, false); + assertFalse(filter.isArtifactIncluded(artifact)); - filter.setOverWriteSnapshots( true ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + filter.setOverWriteSnapshots(true); + assertTrue(filter.isArtifactIncluded(artifact)); } - public void testDestFileSubPerType() - throws MojoExecutionException, IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileSubPerType() throws MojoExecutionException, IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); Artifact artifact = fact.getSnapshotArtifact(); - filter.setUseSubDirectoryPerType( true ); + filter.setUseSubDirectoryPerType(true); - assertTrue( filter.isArtifactIncluded( artifact ) ); - createFile( artifact, false, true, false ); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); + createFile(artifact, false, true, false); + assertFalse(filter.isArtifactIncluded(artifact)); - filter.setOverWriteSnapshots( true ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + filter.setOverWriteSnapshots(true); + assertTrue(filter.isArtifactIncluded(artifact)); } - public void testDestFileOverwriteIfNewer() - throws MojoExecutionException, IOException, ArtifactFilterException - { - DestFileFilter filter = new DestFileFilter( outputFolder ); + public void testDestFileOverwriteIfNewer() throws MojoExecutionException, IOException, ArtifactFilterException { + DestFileFilter filter = new DestFileFilter(outputFolder); - fact.setCreateFiles( true ); + fact.setCreateFiles(true); Artifact artifact = fact.getSnapshotArtifact(); File artifactFile = artifact.getFile(); - assertTrue( artifactFile.setLastModified( artifactFile.lastModified() ) ); - filter.setOverWriteIfNewer( true ); + assertTrue(artifactFile.setLastModified(artifactFile.lastModified())); + filter.setOverWriteIfNewer(true); // should pass because the file doesn't exist yet. - assertTrue( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); // create the file in the destination - File destFile = createFile( artifact, false, false, false ); + File destFile = createFile(artifact, false, false, false); // set the last modified timestamp to be older than the source - assertTrue( destFile.setLastModified( artifactFile.lastModified() - 1000 ) ); - assertTrue( filter.isArtifactIncluded( artifact ) ); + assertTrue(destFile.setLastModified(artifactFile.lastModified() - 1000)); + assertTrue(filter.isArtifactIncluded(artifact)); // now set the last modified timestamp to be newer than the source - assertTrue( destFile.setLastModified( artifactFile.lastModified() + 1000 ) ); + assertTrue(destFile.setLastModified(artifactFile.lastModified() + 1000)); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertFalse(filter.isArtifactIncluded(artifact)); } - public void testGettersSetters() - { - DestFileFilter filter = new DestFileFilter( null ); - assertNull( filter.getOutputFileDirectory() ); - filter.setOutputFileDirectory( outputFolder ); - assertSame( outputFolder, filter.getOutputFileDirectory() ); - - filter.setOverWriteIfNewer( true ); - assertTrue( filter.isOverWriteIfNewer() ); - filter.setOverWriteIfNewer( false ); - assertFalse( filter.isOverWriteIfNewer() ); - - filter.setOverWriteReleases( true ); - assertTrue( filter.isOverWriteReleases() ); - filter.setOverWriteReleases( false ); - assertFalse( filter.isOverWriteReleases() ); - - filter.setOverWriteSnapshots( true ); - assertTrue( filter.isOverWriteSnapshots() ); - filter.setOverWriteSnapshots( false ); - assertFalse( filter.isOverWriteSnapshots() ); - - filter.setUseSubDirectoryPerArtifact( true ); - assertTrue( filter.isUseSubDirectoryPerArtifact() ); - filter.setUseSubDirectoryPerArtifact( false ); - assertFalse( filter.isUseSubDirectoryPerArtifact() ); - - filter.setUseSubDirectoryPerType( true ); - assertTrue( filter.isUseSubDirectoryPerType() ); - filter.setUseSubDirectoryPerType( false ); - assertFalse( filter.isUseSubDirectoryPerType() ); - - filter.setRemoveVersion( true ); - assertTrue( filter.isRemoveVersion() ); - filter.setRemoveVersion( false ); - assertFalse( filter.isRemoveVersion() ); + public void testGettersSetters() { + DestFileFilter filter = new DestFileFilter(null); + assertNull(filter.getOutputFileDirectory()); + filter.setOutputFileDirectory(outputFolder); + assertSame(outputFolder, filter.getOutputFileDirectory()); + + filter.setOverWriteIfNewer(true); + assertTrue(filter.isOverWriteIfNewer()); + filter.setOverWriteIfNewer(false); + assertFalse(filter.isOverWriteIfNewer()); + + filter.setOverWriteReleases(true); + assertTrue(filter.isOverWriteReleases()); + filter.setOverWriteReleases(false); + assertFalse(filter.isOverWriteReleases()); + + filter.setOverWriteSnapshots(true); + assertTrue(filter.isOverWriteSnapshots()); + filter.setOverWriteSnapshots(false); + assertFalse(filter.isOverWriteSnapshots()); + + filter.setUseSubDirectoryPerArtifact(true); + assertTrue(filter.isUseSubDirectoryPerArtifact()); + filter.setUseSubDirectoryPerArtifact(false); + assertFalse(filter.isUseSubDirectoryPerArtifact()); + + filter.setUseSubDirectoryPerType(true); + assertTrue(filter.isUseSubDirectoryPerType()); + filter.setUseSubDirectoryPerType(false); + assertFalse(filter.isUseSubDirectoryPerType()); + + filter.setRemoveVersion(true); + assertTrue(filter.isRemoveVersion()); + filter.setRemoveVersion(false); + assertFalse(filter.isRemoveVersion()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestMarkerFileFilter.java b/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestMarkerFileFilter.java index 8069c9d50..31b05e8ae 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestMarkerFileFilter.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestMarkerFileFilter.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.filters; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,38 +7,35 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; - import junit.framework.TestCase; - import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; -import org.apache.maven.plugins.dependency.utils.markers.DefaultFileMarkerHandler; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.SilentLog; +import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; +import org.apache.maven.plugins.dependency.utils.markers.DefaultFileMarkerHandler; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; /** * @author brianf */ -public class TestMarkerFileFilter - extends TestCase -{ +public class TestMarkerFileFilter extends TestCase { Set artifacts = new HashSet<>(); Log log = new SilentLog(); @@ -49,134 +44,114 @@ public class TestMarkerFileFilter DependencyArtifactStubFactory fact; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - outputFolder = new File( "target/markers/" ); - FileUtils.deleteDirectory( outputFolder ); - assertFalse( outputFolder.exists() ); + outputFolder = new File("target/markers/"); + FileUtils.deleteDirectory(outputFolder); + assertFalse(outputFolder.exists()); - this.fact = new DependencyArtifactStubFactory( outputFolder, false ); + this.fact = new DependencyArtifactStubFactory(outputFolder, false); artifacts = fact.getReleaseAndSnapshotArtifacts(); } - protected void tearDown() - throws IOException - { - FileUtils.deleteDirectory( outputFolder ); + protected void tearDown() throws IOException { + FileUtils.deleteDirectory(outputFolder); } - public void testMarkerFile() - throws ArtifactFilterException + public void testMarkerFile() throws ArtifactFilterException { - { - MarkerFileFilter filter = - new MarkerFileFilter( true, true, false, new DefaultFileMarkerHandler( outputFolder ) ); - Set result = filter.filter( artifacts ); - assertEquals( 2, result.size() ); + MarkerFileFilter filter = new MarkerFileFilter(true, true, false, new DefaultFileMarkerHandler(outputFolder)); + Set result = filter.filter(artifacts); + assertEquals(2, result.size()); - filter.setOverWriteReleases( false ); - filter.setOverWriteSnapshots( false ); - result = filter.filter( artifacts ); - assertEquals( 2, result.size() ); + filter.setOverWriteReleases(false); + filter.setOverWriteSnapshots(false); + result = filter.filter(artifacts); + assertEquals(2, result.size()); } - public void testMarkerSnapshots() - throws ArtifactFilterException, MojoExecutionException, IOException + public void testMarkerSnapshots() throws ArtifactFilterException, MojoExecutionException, IOException { - { - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( fact.getSnapshotArtifact(), outputFolder ); + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(fact.getSnapshotArtifact(), outputFolder); handler.setMarker(); - MarkerFileFilter filter = - new MarkerFileFilter( true, false, false, new DefaultFileMarkerHandler( outputFolder ) ); - Set result = filter.filter( artifacts ); - assertEquals( 1, result.size() ); - - filter.setOverWriteSnapshots( true ); - result = filter.filter( artifacts ); - assertEquals( 2, result.size() ); - assertTrue( handler.clearMarker() ); - FileUtils.deleteDirectory( outputFolder ); - assertFalse( outputFolder.exists() ); + MarkerFileFilter filter = new MarkerFileFilter(true, false, false, new DefaultFileMarkerHandler(outputFolder)); + Set result = filter.filter(artifacts); + assertEquals(1, result.size()); + + filter.setOverWriteSnapshots(true); + result = filter.filter(artifacts); + assertEquals(2, result.size()); + assertTrue(handler.clearMarker()); + FileUtils.deleteDirectory(outputFolder); + assertFalse(outputFolder.exists()); } - public void testMarkerRelease() - throws IOException, ArtifactFilterException, MojoExecutionException - { - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( fact.getReleaseArtifact(), outputFolder ); + public void testMarkerRelease() throws IOException, ArtifactFilterException, MojoExecutionException { + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(fact.getReleaseArtifact(), outputFolder); handler.setMarker(); - MarkerFileFilter filter = - new MarkerFileFilter( false, false, false, new DefaultFileMarkerHandler( outputFolder ) ); - Set result = filter.filter( artifacts ); - assertEquals( 1, result.size() ); + MarkerFileFilter filter = new MarkerFileFilter(false, false, false, new DefaultFileMarkerHandler(outputFolder)); + Set result = filter.filter(artifacts); + assertEquals(1, result.size()); - filter.setOverWriteReleases( true ); - result = filter.filter( artifacts ); - assertEquals( 2, result.size() ); + filter.setOverWriteReleases(true); + result = filter.filter(artifacts); + assertEquals(2, result.size()); - assertTrue( handler.clearMarker() ); - FileUtils.deleteDirectory( outputFolder ); - assertFalse( outputFolder.exists() ); + assertTrue(handler.clearMarker()); + FileUtils.deleteDirectory(outputFolder); + assertFalse(outputFolder.exists()); } - public void testMarkerTimestamp() - throws IOException, MojoExecutionException, ArtifactFilterException - { + public void testMarkerTimestamp() throws IOException, MojoExecutionException, ArtifactFilterException { // filter includes release artifact because no marker present // filter includes snapshot artifact because it is newer than marker - DependencyArtifactStubFactory fileFact = new DependencyArtifactStubFactory( outputFolder, true ); + DependencyArtifactStubFactory fileFact = new DependencyArtifactStubFactory(outputFolder, true); Artifact snap = fileFact.getSnapshotArtifact(); Artifact release = fileFact.getReleaseArtifact(); Set tempArtifacts = new HashSet<>(); - tempArtifacts.add( snap ); - tempArtifacts.add( release ); - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( snap, outputFolder ); + tempArtifacts.add(snap); + tempArtifacts.add(release); + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(snap, outputFolder); handler.setMarker(); - assertTrue( snap.getFile().setLastModified( snap.getFile().lastModified() + 1500 ) ); - MarkerFileFilter filter = - new MarkerFileFilter( false, false, true, new DefaultFileMarkerHandler( outputFolder ) ); - Set result = filter.filter( tempArtifacts ); - assertEquals( 2, result.size() ); + assertTrue(snap.getFile().setLastModified(snap.getFile().lastModified() + 1500)); + MarkerFileFilter filter = new MarkerFileFilter(false, false, true, new DefaultFileMarkerHandler(outputFolder)); + Set result = filter.filter(tempArtifacts); + assertEquals(2, result.size()); // update marker; filter won't include snapshot because timestamps equal handler.setMarker(); - result = filter.filter( tempArtifacts ); - assertEquals( 1, result.size() ); + result = filter.filter(tempArtifacts); + assertEquals(1, result.size()); // filter won't include snapshot because it is older than marker - assertTrue( snap.getFile().setLastModified( snap.getFile().lastModified() - 10000 ) ); + assertTrue(snap.getFile().setLastModified(snap.getFile().lastModified() - 10000)); - result = filter.filter( tempArtifacts ); - assertEquals( 1, result.size() ); + result = filter.filter(tempArtifacts); + assertEquals(1, result.size()); - assertTrue( handler.clearMarker() ); - assertFalse( handler.isMarkerSet() ); + assertTrue(handler.clearMarker()); + assertFalse(handler.isMarkerSet()); snap.getFile().delete(); release.getFile().delete(); - FileUtils.deleteDirectory( outputFolder ); - assertFalse( outputFolder.exists() ); + FileUtils.deleteDirectory(outputFolder); + assertFalse(outputFolder.exists()); } - public void testGettersSetters() - { - MarkerFileFilter filter = - new MarkerFileFilter( true, false, true, new DefaultFileMarkerHandler( outputFolder ) ); - assertTrue( filter.isOverWriteReleases() ); - assertFalse( filter.isOverWriteSnapshots() ); - assertTrue( filter.isOverWriteIfNewer() ); - - filter.setOverWriteReleases( false ); - filter.setOverWriteSnapshots( true ); - filter.setOverWriteIfNewer( false ); + public void testGettersSetters() { + MarkerFileFilter filter = new MarkerFileFilter(true, false, true, new DefaultFileMarkerHandler(outputFolder)); + assertTrue(filter.isOverWriteReleases()); + assertFalse(filter.isOverWriteSnapshots()); + assertTrue(filter.isOverWriteIfNewer()); - assertFalse( filter.isOverWriteReleases() ); - assertTrue( filter.isOverWriteSnapshots() ); - assertFalse( filter.isOverWriteIfNewer() ); + filter.setOverWriteReleases(false); + filter.setOverWriteSnapshots(true); + filter.setOverWriteIfNewer(false); + assertFalse(filter.isOverWriteReleases()); + assertTrue(filter.isOverWriteSnapshots()); + assertFalse(filter.isOverWriteIfNewer()); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestResolveMarkerFileFilter.java b/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestResolveMarkerFileFilter.java index 4c36fe438..8b4ac4078 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestResolveMarkerFileFilter.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestResolveMarkerFileFilter.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.filters; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,41 +7,38 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.filters; + /** - * + * */ - import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; - import junit.framework.TestCase; - import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; -import org.apache.maven.plugins.dependency.utils.markers.SourcesFileMarkerHandler; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.SilentLog; +import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; +import org.apache.maven.plugins.dependency.utils.markers.SourcesFileMarkerHandler; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; /** * @author brianf */ -public class TestResolveMarkerFileFilter - extends TestCase -{ +public class TestResolveMarkerFileFilter extends TestCase { Set artifacts = new HashSet<>(); Log log = new SilentLog(); @@ -52,38 +47,31 @@ public class TestResolveMarkerFileFilter DependencyArtifactStubFactory fact; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - outputFolder = new File( "target/markers/" ); - FileUtils.deleteDirectory( outputFolder ); - assertFalse( outputFolder.exists() ); + outputFolder = new File("target/markers/"); + FileUtils.deleteDirectory(outputFolder); + assertFalse(outputFolder.exists()); - this.fact = new DependencyArtifactStubFactory( outputFolder, false ); + this.fact = new DependencyArtifactStubFactory(outputFolder, false); artifacts = fact.getReleaseAndSnapshotArtifacts(); } - protected void tearDown() - throws IOException - { - FileUtils.deleteDirectory( outputFolder ); + protected void tearDown() throws IOException { + FileUtils.deleteDirectory(outputFolder); } - public void testResolveFile() - throws IOException, ArtifactFilterException, MojoExecutionException - { - SourcesFileMarkerHandler handler = new SourcesFileMarkerHandler( outputFolder ); + public void testResolveFile() throws IOException, ArtifactFilterException, MojoExecutionException { + SourcesFileMarkerHandler handler = new SourcesFileMarkerHandler(outputFolder); Artifact artifact = fact.getReleaseArtifact(); - handler.setArtifact( artifact ); + handler.setArtifact(artifact); - ResolveFileFilter filter = new ResolveFileFilter( handler ); + ResolveFileFilter filter = new ResolveFileFilter(handler); - assertTrue( filter.isArtifactIncluded( artifact ) ); + assertTrue(filter.isArtifactIncluded(artifact)); handler.setMarker(); - assertFalse( filter.isArtifactIncluded( artifact ) ); + assertFalse(filter.isArtifactIncluded(artifact)); } - } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestDefaultMarkerFileHandler.java b/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestDefaultMarkerFileHandler.java index 4d328cba9..7d793e17f 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestDefaultMarkerFileHandler.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestDefaultMarkerFileHandler.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.markers; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,23 +7,22 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -33,156 +30,136 @@ import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.testUtils.stubs.StubDefaultFileMarkerHandler; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.SilentLog; +import org.apache.maven.plugins.dependency.testUtils.stubs.StubDefaultFileMarkerHandler; /** * @author brianf */ -public class TestDefaultMarkerFileHandler - extends TestCase -{ +public class TestDefaultMarkerFileHandler extends TestCase { List artifacts = new ArrayList<>(); Log log = new SilentLog(); File outputFolder; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); ArtifactHandler ah = new DefaultArtifactHandler(); - VersionRange vr = VersionRange.createFromVersion( "1.1" ); - Artifact artifact = new DefaultArtifact( "test", "1", vr, Artifact.SCOPE_COMPILE, "jar", "", ah, false ); - artifacts.add( artifact ); - artifact = new DefaultArtifact( "test", "2", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false ); - artifacts.add( artifact ); - artifact = new DefaultArtifact( "test", "3", vr, Artifact.SCOPE_TEST, "sources", "", ah, false ); - artifacts.add( artifact ); - artifact = new DefaultArtifact( "test", "4", vr, Artifact.SCOPE_RUNTIME, "zip", "", ah, false ); - artifacts.add( artifact ); - - outputFolder = new File( "target/markers/" ); - FileUtils.deleteDirectory( this.outputFolder ); - assertFalse( outputFolder.exists() ); + VersionRange vr = VersionRange.createFromVersion("1.1"); + Artifact artifact = new DefaultArtifact("test", "1", vr, Artifact.SCOPE_COMPILE, "jar", "", ah, false); + artifacts.add(artifact); + artifact = new DefaultArtifact("test", "2", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false); + artifacts.add(artifact); + artifact = new DefaultArtifact("test", "3", vr, Artifact.SCOPE_TEST, "sources", "", ah, false); + artifacts.add(artifact); + artifact = new DefaultArtifact("test", "4", vr, Artifact.SCOPE_RUNTIME, "zip", "", ah, false); + artifacts.add(artifact); + + outputFolder = new File("target/markers/"); + FileUtils.deleteDirectory(this.outputFolder); + assertFalse(outputFolder.exists()); } - protected void tearDown() - throws IOException - { - FileUtils.deleteDirectory( this.outputFolder ); + protected void tearDown() throws IOException { + FileUtils.deleteDirectory(this.outputFolder); } - public void testSetMarker() - throws MojoExecutionException - { - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( artifacts.get( 0 ), this.outputFolder ); - assertFalse( handler.isMarkerSet() ); + public void testSetMarker() throws MojoExecutionException { + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(artifacts.get(0), this.outputFolder); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } - public void testMarkerFile() - throws MojoExecutionException, IOException - { - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( artifacts.get( 0 ), this.outputFolder ); + public void testMarkerFile() throws MojoExecutionException, IOException { + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(artifacts.get(0), this.outputFolder); File handle = handler.getMarkerFile(); - assertFalse( handle.exists() ); - assertFalse( handler.isMarkerSet() ); + assertFalse(handle.exists()); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handle.exists() ); + assertTrue(handler.isMarkerSet()); + assertTrue(handle.exists()); handle.delete(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handle.createNewFile(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handle.exists() ); + assertFalse(handle.exists()); } - public void testMarkerTimeStamp() - throws MojoExecutionException, IOException, InterruptedException - { - File theFile = new File( outputFolder, "theFile.jar" ); + public void testMarkerTimeStamp() throws MojoExecutionException, IOException, InterruptedException { + File theFile = new File(outputFolder, "theFile.jar"); outputFolder.mkdirs(); theFile.createNewFile(); - Artifact theArtifact = artifacts.get( 0 ); - theArtifact.setFile( theFile ); - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( theArtifact, this.outputFolder ); - assertFalse( handler.isMarkerSet() ); + Artifact theArtifact = artifacts.get(0); + theArtifact.setFile(theFile); + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(theArtifact, this.outputFolder); + assertFalse(handler.isMarkerSet()); // if the marker is not set, assume it is infinately older than the // artifact. - assertTrue( handler.isMarkerOlder( theArtifact ) ); + assertTrue(handler.isMarkerOlder(theArtifact)); handler.setMarker(); - assertFalse( handler.isMarkerOlder( theArtifact ) ); + assertFalse(handler.isMarkerOlder(theArtifact)); - assertTrue( theFile.setLastModified( theFile.lastModified() + 60000 ) ); - assertTrue( handler.isMarkerOlder( theArtifact ) ); + assertTrue(theFile.setLastModified(theFile.lastModified() + 60000)); + assertTrue(handler.isMarkerOlder(theArtifact)); theFile.delete(); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } - public void testMarkerFileException() - { + public void testMarkerFileException() { // this stub wraps the file with an object to throw exceptions - StubDefaultFileMarkerHandler handler = - new StubDefaultFileMarkerHandler( artifacts.get( 0 ), this.outputFolder ); - try - { + StubDefaultFileMarkerHandler handler = new StubDefaultFileMarkerHandler(artifacts.get(0), this.outputFolder); + try { handler.setMarker(); - fail( "Expected an Exception here" ); - } - catch ( MojoExecutionException e ) - { + fail("Expected an Exception here"); + } catch (MojoExecutionException e) { } } - public void testGetterSetter() - { - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( null, null ); - assertNull( handler.getArtifact() ); - handler.setArtifact( artifacts.get( 0 ) ); - assertSame( artifacts.get( 0 ), handler.getArtifact() ); + public void testGetterSetter() { + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(null, null); + assertNull(handler.getArtifact()); + handler.setArtifact(artifacts.get(0)); + assertSame(artifacts.get(0), handler.getArtifact()); - assertNull( handler.getMarkerFilesDirectory() ); - handler.setMarkerFilesDirectory( outputFolder ); - assertSame( outputFolder, handler.getMarkerFilesDirectory() ); + assertNull(handler.getMarkerFilesDirectory()); + handler.setMarkerFilesDirectory(outputFolder); + assertSame(outputFolder, handler.getMarkerFilesDirectory()); } - public void testNullParent() - throws MojoExecutionException - { + public void testNullParent() throws MojoExecutionException { // the parent isn't set so this will create the marker in the local // folder. We must clear the // marker to avoid leaving test droppings in root. - DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler( null, null ); - handler.setArtifact( artifacts.get( 0 ) ); + DefaultFileMarkerHandler handler = new DefaultFileMarkerHandler(null, null); + handler.setArtifact(artifacts.get(0)); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestSourcesMarkerFileHandler.java b/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestSourcesMarkerFileHandler.java index fa36d1ac7..9024b1237 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestSourcesMarkerFileHandler.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestSourcesMarkerFileHandler.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.markers; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,288 +7,257 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; - import junit.framework.TestCase; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.testUtils.stubs.StubSourcesFileMarkerHandler; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.SilentLog; +import org.apache.maven.plugins.dependency.testUtils.stubs.StubSourcesFileMarkerHandler; /** * @author brianf */ -public class TestSourcesMarkerFileHandler - extends TestCase -{ +public class TestSourcesMarkerFileHandler extends TestCase { List artifacts = new ArrayList<>(); Log log = new SilentLog(); File outputFolder; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); ArtifactHandler ah = new DefaultArtifactHandler(); - VersionRange vr = VersionRange.createFromVersion( "1.1" ); - Artifact artifact = new DefaultArtifact( "test", "1", vr, Artifact.SCOPE_COMPILE, "jar", "", ah, false ); - artifacts.add( artifact ); - artifact = new DefaultArtifact( "test", "2", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false ); - artifacts.add( artifact ); - artifact = new DefaultArtifact( "test", "3", vr, Artifact.SCOPE_TEST, "sources", "", ah, false ); - artifacts.add( artifact ); - artifact = new DefaultArtifact( "test", "4", vr, Artifact.SCOPE_RUNTIME, "zip", "", ah, false ); - artifacts.add( artifact ); + VersionRange vr = VersionRange.createFromVersion("1.1"); + Artifact artifact = new DefaultArtifact("test", "1", vr, Artifact.SCOPE_COMPILE, "jar", "", ah, false); + artifacts.add(artifact); + artifact = new DefaultArtifact("test", "2", vr, Artifact.SCOPE_PROVIDED, "war", "", ah, false); + artifacts.add(artifact); + artifact = new DefaultArtifact("test", "3", vr, Artifact.SCOPE_TEST, "sources", "", ah, false); + artifacts.add(artifact); + artifact = new DefaultArtifact("test", "4", vr, Artifact.SCOPE_RUNTIME, "zip", "", ah, false); + artifacts.add(artifact); // pick random output location Random a = new Random(); - outputFolder = new File( "target/markers" + a.nextLong() + "/" ); + outputFolder = new File("target/markers" + a.nextLong() + "/"); outputFolder.delete(); - assertFalse( outputFolder.exists() ); + assertFalse(outputFolder.exists()); } - protected void tearDown() - { + protected void tearDown() { outputFolder.delete(); } - public void testSetMarkerResolved() - throws MojoExecutionException - { - DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, true ); - assertFalse( handler.isMarkerSet() ); + public void testSetMarkerResolved() throws MojoExecutionException { + DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, true); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handler.setMarker(); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); handler.clearMarker(); outputFolder.delete(); - assertFalse( outputFolder.exists() ); + assertFalse(outputFolder.exists()); } - public void testSetMarkerUnresolved() - throws MojoExecutionException - { - DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, false ); - assertFalse( handler.isMarkerSet() ); + public void testSetMarkerUnresolved() throws MojoExecutionException { + DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, false); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handler.setMarker(); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); handler.clearMarker(); outputFolder.delete(); - assertFalse( outputFolder.exists() ); + assertFalse(outputFolder.exists()); } - public void testBothMarkers() - throws MojoExecutionException - { - DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler( artifacts.get( 1 ), this.outputFolder, true ); - DefaultFileMarkerHandler handler2 = - new SourcesFileMarkerHandler( artifacts.get( 1 ), this.outputFolder, false ); + public void testBothMarkers() throws MojoExecutionException { + DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler(artifacts.get(1), this.outputFolder, true); + DefaultFileMarkerHandler handler2 = new SourcesFileMarkerHandler(artifacts.get(1), this.outputFolder, false); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handler2.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); + assertTrue(handler2.isMarkerSet()); handler2.clearMarker(); - assertFalse( handler.isMarkerSet() ); - assertFalse( handler2.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); + assertFalse(handler2.isMarkerSet()); outputFolder.delete(); - assertFalse( outputFolder.exists() ); + assertFalse(outputFolder.exists()); } - public void testMarkerFile() - throws MojoExecutionException, IOException - { - DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, true ); - DefaultFileMarkerHandler handler2 = - new SourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, false ); + public void testMarkerFile() throws MojoExecutionException, IOException { + DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, true); + DefaultFileMarkerHandler handler2 = new SourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, false); File handle = handler.getMarkerFile(); File handle2 = handler2.getMarkerFile(); - assertFalse( handle.exists() ); - assertFalse( handler.isMarkerSet() ); - assertFalse( handle2.exists() ); - assertFalse( handler2.isMarkerSet() ); + assertFalse(handle.exists()); + assertFalse(handler.isMarkerSet()); + assertFalse(handle2.exists()); + assertFalse(handler2.isMarkerSet()); // if either file exists, the marker is set handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handle.exists() ); - assertTrue( handler2.isMarkerSet() ); - assertFalse( handle2.exists() ); + assertTrue(handler.isMarkerSet()); + assertTrue(handle.exists()); + assertTrue(handler2.isMarkerSet()); + assertFalse(handle2.exists()); // if either file exists, the marker is set // setting 1 will clear the other marker handler2.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertFalse( handle.exists() ); - assertTrue( handler2.isMarkerSet() ); - assertTrue( handle2.exists() ); + assertTrue(handler.isMarkerSet()); + assertFalse(handle.exists()); + assertTrue(handler2.isMarkerSet()); + assertTrue(handle2.exists()); // reset file for next test handle.createNewFile(); // only delete one, should be still true handle2.delete(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handler2.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); + assertTrue(handler2.isMarkerSet()); // delete the 2nd, should be false. handle.delete(); - assertFalse( handler.isMarkerSet() ); - assertFalse( handler2.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); + assertFalse(handler2.isMarkerSet()); handle.createNewFile(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handler2.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); + assertTrue(handler2.isMarkerSet()); handler.clearMarker(); - assertFalse( handle.exists() ); + assertFalse(handle.exists()); handler2.clearMarker(); - assertFalse( handle2.exists() ); + assertFalse(handle2.exists()); handle.delete(); handle2.delete(); outputFolder.delete(); - assertFalse( outputFolder.exists() ); + assertFalse(outputFolder.exists()); } - public void testMarkerTimeStampResolved() - throws MojoExecutionException, IOException, InterruptedException - { - doTestMarkerTimeStamp( true ); + public void testMarkerTimeStampResolved() throws MojoExecutionException, IOException, InterruptedException { + doTestMarkerTimeStamp(true); } - public void testMarkerTimeStampUnResolved() - throws MojoExecutionException, IOException, InterruptedException - { - doTestMarkerTimeStamp( false ); + public void testMarkerTimeStampUnResolved() throws MojoExecutionException, IOException, InterruptedException { + doTestMarkerTimeStamp(false); } - public void doTestMarkerTimeStamp( boolean resolved ) - throws MojoExecutionException, IOException, InterruptedException - { - File theFile = new File( outputFolder, "theFile.jar" ); + public void doTestMarkerTimeStamp(boolean resolved) + throws MojoExecutionException, IOException, InterruptedException { + File theFile = new File(outputFolder, "theFile.jar"); outputFolder.mkdirs(); theFile.createNewFile(); - Artifact theArtifact = artifacts.get( 0 ); - theArtifact.setFile( theFile ); + Artifact theArtifact = artifacts.get(0); + theArtifact.setFile(theFile); SourcesFileMarkerHandler resolvedHandler = - new SourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, resolved ); + new SourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, resolved); SourcesFileMarkerHandler unResolvedHandler = - new SourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, !resolved ); + new SourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, !resolved); - assertFalse( resolvedHandler.isMarkerSet() ); - assertFalse( unResolvedHandler.isMarkerSet() ); + assertFalse(resolvedHandler.isMarkerSet()); + assertFalse(unResolvedHandler.isMarkerSet()); // if the marker is not set, assume it is infinately older than the // artifact. - assertTrue( resolvedHandler.isMarkerOlder( theArtifact ) ); - assertTrue( unResolvedHandler.isMarkerOlder( theArtifact ) ); + assertTrue(resolvedHandler.isMarkerOlder(theArtifact)); + assertTrue(unResolvedHandler.isMarkerOlder(theArtifact)); resolvedHandler.setMarker(); - assertFalse( resolvedHandler.isMarkerOlder( theArtifact ) ); - assertFalse( unResolvedHandler.isMarkerOlder( theArtifact ) ); + assertFalse(resolvedHandler.isMarkerOlder(theArtifact)); + assertFalse(unResolvedHandler.isMarkerOlder(theArtifact)); resolvedHandler.clearMarker(); unResolvedHandler.setMarker(); - assertFalse( resolvedHandler.isMarkerOlder( theArtifact ) ); - assertFalse( unResolvedHandler.isMarkerOlder( theArtifact ) ); + assertFalse(resolvedHandler.isMarkerOlder(theArtifact)); + assertFalse(unResolvedHandler.isMarkerOlder(theArtifact)); - assertTrue( theFile.setLastModified( theFile.lastModified() + 60000 ) ); - assertTrue( resolvedHandler.isMarkerOlder( theArtifact ) ); - assertTrue( unResolvedHandler.isMarkerOlder( theArtifact ) ); + assertTrue(theFile.setLastModified(theFile.lastModified() + 60000)); + assertTrue(resolvedHandler.isMarkerOlder(theArtifact)); + assertTrue(unResolvedHandler.isMarkerOlder(theArtifact)); theFile.delete(); resolvedHandler.clearMarker(); - assertFalse( resolvedHandler.isMarkerSet() ); + assertFalse(resolvedHandler.isMarkerSet()); } - public void testMarkerFileException() - { + public void testMarkerFileException() { // this stub wraps the file with an object to throw exceptions StubSourcesFileMarkerHandler handler = - new StubSourcesFileMarkerHandler( artifacts.get( 0 ), this.outputFolder, true ); - try - { + new StubSourcesFileMarkerHandler(artifacts.get(0), this.outputFolder, true); + try { handler.setMarker(); - fail( "Expected an Exception here" ); - } - catch ( MojoExecutionException e ) - { + fail("Expected an Exception here"); + } catch (MojoExecutionException e) { } } - public void testMarkerFileResolvedSetter() - { - SourcesFileMarkerHandler handler = new SourcesFileMarkerHandler( null, null, true ); - assertTrue( handler.isResolved() ); - handler.setResolved( false ); - assertFalse( handler.isResolved() ); + public void testMarkerFileResolvedSetter() { + SourcesFileMarkerHandler handler = new SourcesFileMarkerHandler(null, null, true); + assertTrue(handler.isResolved()); + handler.setResolved(false); + assertFalse(handler.isResolved()); } - public void testNullParent() - throws MojoExecutionException - { + public void testNullParent() throws MojoExecutionException { // the parent isn't set so this will create the marker in the local // folder. We must clear the // marker to avoid leaving test droppings in root. - DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler( null, null, false ); - handler.setArtifact( artifacts.get( 0 ) ); + DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler(null, null, false); + handler.setArtifact(artifacts.get(0)); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } - public void testNullParentResolved() - throws MojoExecutionException - { + public void testNullParentResolved() throws MojoExecutionException { // the parent isn't set so this will create the marker in the local // folder. We must clear the // marker to avoid leaving test droppings in root. - DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler( null, null, true ); - handler.setArtifact( artifacts.get( 0 ) ); + DefaultFileMarkerHandler handler = new SourcesFileMarkerHandler(null, null, true); + handler.setArtifact(artifacts.get(0)); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); - + assertFalse(handler.isMarkerSet()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestUnpackMarkerFileHandler.java b/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestUnpackMarkerFileHandler.java index 8501b217f..0038d2a2b 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestUnpackMarkerFileHandler.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestUnpackMarkerFileHandler.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.markers; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,34 +7,32 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.markers; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; - import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; -import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; -import org.apache.maven.plugins.dependency.testUtils.stubs.StubUnpackFileMarkerHandler; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.apache.maven.plugin.testing.SilentLog; +import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem; +import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; +import org.apache.maven.plugins.dependency.testUtils.stubs.StubUnpackFileMarkerHandler; -public class TestUnpackMarkerFileHandler - extends AbstractMojoTestCase -{ +public class TestUnpackMarkerFileHandler extends AbstractMojoTestCase { List artifactItems = new ArrayList<>(); Log log = new SilentLog(); @@ -47,233 +43,211 @@ public class TestUnpackMarkerFileHandler protected DependencyArtifactStubFactory stubFactory; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - testDir = new File( getBasedir(), "target" + File.separatorChar + "unit-tests" + File.separatorChar - + "unpack-markers" + File.separatorChar ); - FileUtils.deleteDirectory( testDir ); - assertFalse( testDir.exists() ); + testDir = new File( + getBasedir(), + "target" + File.separatorChar + "unit-tests" + File.separatorChar + "unpack-markers" + + File.separatorChar); + FileUtils.deleteDirectory(testDir); + assertFalse(testDir.exists()); - stubFactory = new DependencyArtifactStubFactory( this.testDir, false ); - Artifact artifact = stubFactory.createArtifact( "test", "test", "1" ); + stubFactory = new DependencyArtifactStubFactory(this.testDir, false); + Artifact artifact = stubFactory.createArtifact("test", "test", "1"); ArtifactItem artifactItem; - stubFactory.getArtifactItem( artifact ); - artifactItems.add( stubFactory.getArtifactItem( stubFactory.createArtifact( "test", "test", "1" ) ) ); - artifact = stubFactory.createArtifact( "test2", "test2", "2" ); - artifactItem = new ArtifactItem( artifact ); - artifactItem.setIncludes( "**/*.xml" ); - artifactItems.add( artifactItem ); - artifact = stubFactory.createArtifact( "test3", "test3", "3" ); - artifactItem = new ArtifactItem( artifact ); - artifactItem.setExcludes( "**/*.class" ); - artifactItems.add( artifactItem ); - artifact = stubFactory.createArtifact( "test4", "test4", "4" ); - artifactItem = new ArtifactItem( artifact ); - artifactItem.setIncludes( "**/*.xml" ); - artifactItem.setExcludes( "**/*.class" ); - artifactItems.add( artifactItem ); - - outputFolder = new File( "target/markers/" ); - FileUtils.deleteDirectory( this.outputFolder ); - assertFalse( outputFolder.exists() ); + stubFactory.getArtifactItem(artifact); + artifactItems.add(stubFactory.getArtifactItem(stubFactory.createArtifact("test", "test", "1"))); + artifact = stubFactory.createArtifact("test2", "test2", "2"); + artifactItem = new ArtifactItem(artifact); + artifactItem.setIncludes("**/*.xml"); + artifactItems.add(artifactItem); + artifact = stubFactory.createArtifact("test3", "test3", "3"); + artifactItem = new ArtifactItem(artifact); + artifactItem.setExcludes("**/*.class"); + artifactItems.add(artifactItem); + artifact = stubFactory.createArtifact("test4", "test4", "4"); + artifactItem = new ArtifactItem(artifact); + artifactItem.setIncludes("**/*.xml"); + artifactItem.setExcludes("**/*.class"); + artifactItems.add(artifactItem); + + outputFolder = new File("target/markers/"); + FileUtils.deleteDirectory(this.outputFolder); + assertFalse(outputFolder.exists()); } - protected void tearDown() - throws IOException - { - FileUtils.deleteDirectory( this.outputFolder ); + protected void tearDown() throws IOException { + FileUtils.deleteDirectory(this.outputFolder); } /** * Assert that default functionality still exists - * + * * @throws MojoExecutionException in case of an error. */ - public void testSetMarker() - throws MojoExecutionException - { - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( artifactItems.get( 0 ), this.outputFolder ); - assertFalse( handler.isMarkerSet() ); + public void testSetMarker() throws MojoExecutionException { + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(artifactItems.get(0), this.outputFolder); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } - public void testMarkerFile() - throws MojoExecutionException, IOException - { - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( artifactItems.get( 0 ), this.outputFolder ); + public void testMarkerFile() throws MojoExecutionException, IOException { + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(artifactItems.get(0), this.outputFolder); File handle = handler.getMarkerFile(); - assertFalse( handle.exists() ); - assertFalse( handler.isMarkerSet() ); + assertFalse(handle.exists()); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handle.exists() ); + assertTrue(handler.isMarkerSet()); + assertTrue(handle.exists()); handle.delete(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handle.createNewFile(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handle.exists() ); + assertFalse(handle.exists()); } - public void testMarkerTimeStamp() - throws MojoExecutionException, IOException, InterruptedException - { - File theFile = new File( outputFolder, "theFile.jar" ); + public void testMarkerTimeStamp() throws MojoExecutionException, IOException, InterruptedException { + File theFile = new File(outputFolder, "theFile.jar"); outputFolder.mkdirs(); theFile.createNewFile(); - ArtifactItem theArtifactItem = artifactItems.get( 0 ); + ArtifactItem theArtifactItem = artifactItems.get(0); Artifact theArtifact = theArtifactItem.getArtifact(); - theArtifact.setFile( theFile ); - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( theArtifactItem, this.outputFolder ); - assertFalse( handler.isMarkerSet() ); + theArtifact.setFile(theFile); + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(theArtifactItem, this.outputFolder); + assertFalse(handler.isMarkerSet()); // if the marker is not set, assume it is infinately older than the // artifact. - assertTrue( handler.isMarkerOlder( theArtifact ) ); + assertTrue(handler.isMarkerOlder(theArtifact)); handler.setMarker(); - assertFalse( handler.isMarkerOlder( theArtifact ) ); + assertFalse(handler.isMarkerOlder(theArtifact)); - assertTrue( theFile.setLastModified( theFile.lastModified() + 60000 ) ); - assertTrue( handler.isMarkerOlder( theArtifact ) ); + assertTrue(theFile.setLastModified(theFile.lastModified() + 60000)); + assertTrue(handler.isMarkerOlder(theArtifact)); theFile.delete(); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } - public void testMarkerFileException() - { + public void testMarkerFileException() { // this stub wraps the file with an object to throw exceptions - StubUnpackFileMarkerHandler handler = - new StubUnpackFileMarkerHandler( artifactItems.get( 0 ), this.outputFolder ); - try - { + StubUnpackFileMarkerHandler handler = new StubUnpackFileMarkerHandler(artifactItems.get(0), this.outputFolder); + try { handler.setMarker(); - fail( "Expected an Exception here" ); - } - catch ( MojoExecutionException e ) - { + fail("Expected an Exception here"); + } catch (MojoExecutionException e) { } } - public void testGetterSetter() - { - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( null, null ); - assertNull( handler.getArtifactItem() ); - assertNull( handler.getArtifact() ); - handler.setArtifactItem( artifactItems.get( 0 ) ); - assertSame( artifactItems.get( 0 ), handler.getArtifactItem() ); - assertSame( artifactItems.get( 0 ).getArtifact(), handler.getArtifact() ); - - assertNull( handler.getMarkerFilesDirectory() ); - handler.setMarkerFilesDirectory( outputFolder ); - assertSame( outputFolder, handler.getMarkerFilesDirectory() ); + public void testGetterSetter() { + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(null, null); + assertNull(handler.getArtifactItem()); + assertNull(handler.getArtifact()); + handler.setArtifactItem(artifactItems.get(0)); + assertSame(artifactItems.get(0), handler.getArtifactItem()); + assertSame(artifactItems.get(0).getArtifact(), handler.getArtifact()); + + assertNull(handler.getMarkerFilesDirectory()); + handler.setMarkerFilesDirectory(outputFolder); + assertSame(outputFolder, handler.getMarkerFilesDirectory()); } - public void testNullParent() - throws MojoExecutionException - { + public void testNullParent() throws MojoExecutionException { // the parent isn't set so this will create the marker in the local // folder. We must clear the // marker to avoid leaving test droppings in root. - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( null, null ); - handler.setArtifactItem( artifactItems.get( 0 ) ); + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(null, null); + handler.setArtifactItem(artifactItems.get(0)); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); } - public void testIncludesMarker() - throws MojoExecutionException, IOException - { - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( artifactItems.get( 1 ), outputFolder ); + public void testIncludesMarker() throws MojoExecutionException, IOException { + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(artifactItems.get(1), outputFolder); File handle = handler.getMarkerFile(); - assertFalse( handle.exists() ); - assertFalse( handler.isMarkerSet() ); + assertFalse(handle.exists()); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handle.exists() ); - String hashCode = "" + ( "**/*.xml".hashCode() ); - assertTrue( handle.getName().contains( hashCode ) ); + assertTrue(handler.isMarkerSet()); + assertTrue(handle.exists()); + String hashCode = "" + ("**/*.xml".hashCode()); + assertTrue(handle.getName().contains(hashCode)); handle.delete(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handle.createNewFile(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handle.exists() ); + assertFalse(handle.exists()); } - public void testExcludesMarker() - throws MojoExecutionException, IOException - { - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( artifactItems.get( 2 ), outputFolder ); + public void testExcludesMarker() throws MojoExecutionException, IOException { + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(artifactItems.get(2), outputFolder); File handle = handler.getMarkerFile(); - assertFalse( handle.exists() ); - assertFalse( handler.isMarkerSet() ); + assertFalse(handle.exists()); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handle.exists() ); - String hashCode = "" + ( "**/*.class".hashCode() ); - assertTrue( handle.getName().contains( hashCode ) ); + assertTrue(handler.isMarkerSet()); + assertTrue(handle.exists()); + String hashCode = "" + ("**/*.class".hashCode()); + assertTrue(handle.getName().contains(hashCode)); handle.delete(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handle.createNewFile(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handle.exists() ); + assertFalse(handle.exists()); } - public void testIncludesExcludesMarker() - throws MojoExecutionException, IOException - { - UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler( artifactItems.get( 3 ), outputFolder ); + public void testIncludesExcludesMarker() throws MojoExecutionException, IOException { + UnpackFileMarkerHandler handler = new UnpackFileMarkerHandler(artifactItems.get(3), outputFolder); File handle = handler.getMarkerFile(); - assertFalse( handle.exists() ); - assertFalse( handler.isMarkerSet() ); + assertFalse(handle.exists()); + assertFalse(handler.isMarkerSet()); handler.setMarker(); - assertTrue( handler.isMarkerSet() ); - assertTrue( handle.exists() ); - String hashCode = "" + ( 0 + "**/*.class".hashCode() + "**/*.xml".hashCode() ); - assertTrue( handle.getName().contains( hashCode ) ); + assertTrue(handler.isMarkerSet()); + assertTrue(handle.exists()); + String hashCode = "" + (0 + "**/*.class".hashCode() + "**/*.xml".hashCode()); + assertTrue(handle.getName().contains(hashCode)); handle.delete(); - assertFalse( handler.isMarkerSet() ); + assertFalse(handler.isMarkerSet()); handle.createNewFile(); - assertTrue( handler.isMarkerSet() ); + assertTrue(handler.isMarkerSet()); handler.clearMarker(); - assertFalse( handle.exists() ); + assertFalse(handle.exists()); } } diff --git a/src/test/java/org/apache/maven/plugins/dependency/utils/translators/TestClassifierTypeTranslator.java b/src/test/java/org/apache/maven/plugins/dependency/utils/translators/TestClassifierTypeTranslator.java index 1bbf0db07..4fa377f23 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/utils/translators/TestClassifierTypeTranslator.java +++ b/src/test/java/org/apache/maven/plugins/dependency/utils/translators/TestClassifierTypeTranslator.java @@ -1,6 +1,4 @@ -package org.apache.maven.plugins.dependency.utils.translators; - -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -9,21 +7,21 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations - * under the License. + * under the License. */ +package org.apache.maven.plugins.dependency.utils.translators; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.factory.DefaultArtifactFactory; @@ -43,9 +41,7 @@ /** * @author brianf */ -public class TestClassifierTypeTranslator - extends AbstractDependencyMojoTestCase -{ +public class TestClassifierTypeTranslator extends AbstractDependencyMojoTestCase { Set artifacts = new HashSet<>(); ArtifactFactory artifactFactory; @@ -57,152 +53,131 @@ public class TestClassifierTypeTranslator private ArtifactHandlerManager artifactHandlerManager; @Override - protected void setUp() - throws Exception - { - super.setUp( "classifiertype-translator", false ); + protected void setUp() throws Exception { + super.setUp("classifiertype-translator", false); artifactHandlerManager = new DefaultArtifactHandlerManager(); - this.setVariableValueToObject( artifactHandlerManager, "artifactHandlers", new HashMap<>() ); + this.setVariableValueToObject(artifactHandlerManager, "artifactHandlers", new HashMap<>()); artifactFactory = new DefaultArtifactFactory(); - this.setVariableValueToObject( artifactFactory, "artifactHandlerManager", artifactHandlerManager ); + this.setVariableValueToObject(artifactFactory, "artifactHandlerManager", artifactHandlerManager); - artifactRepository = new StubArtifactRepository( null ); + artifactRepository = new StubArtifactRepository(null); - DependencyArtifactStubFactory factory = new DependencyArtifactStubFactory( null, false ); + DependencyArtifactStubFactory factory = new DependencyArtifactStubFactory(null, false); artifacts = factory.getMixedArtifacts(); - LegacySupport legacySupport = lookup( LegacySupport.class ); - MavenSession session = newMavenSession( new MavenProjectStub() ); - legacySupport.setSession( session ); - - installLocalRepository( legacySupport ); + LegacySupport legacySupport = lookup(LegacySupport.class); + MavenSession session = newMavenSession(new MavenProjectStub()); + legacySupport.setSession(session); + installLocalRepository(legacySupport); } - public void testNullClassifier() - { - doTestNullEmptyClassifier( null ); + public void testNullClassifier() { + doTestNullEmptyClassifier(null); } - public void testEmptyClassifier() - { - doTestNullEmptyClassifier( "" ); + public void testEmptyClassifier() { + doTestNullEmptyClassifier(""); } - public void doTestNullEmptyClassifier( String classifier ) - { + public void doTestNullEmptyClassifier(String classifier) { String type = "zip"; - ArtifactTranslator at = new ClassifierTypeTranslator( artifactHandlerManager, classifier, type ); - Set results = at.translate( artifacts, log ); + ArtifactTranslator at = new ClassifierTypeTranslator(artifactHandlerManager, classifier, type); + Set results = at.translate(artifacts, log); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { Iterator resultIter = results.iterator(); boolean found = false; - while ( resultIter.hasNext() ) - { + while (resultIter.hasNext()) { ArtifactCoordinate translatedArtifact = resultIter.next(); - if ( artifact.getArtifactId().equals( translatedArtifact.getArtifactId() ) - && artifact.getGroupId().equals( translatedArtifact.getGroupId() ) - /* && artifact.getScope().equals(translatedArtifact.getScope()) */ ) - { + if (artifact.getArtifactId().equals(translatedArtifact.getArtifactId()) + && artifact.getGroupId().equals(translatedArtifact.getGroupId()) + /* && artifact.getScope().equals(translatedArtifact.getScope()) */ ) { // classifier is null, should be the same as the artifact - assertEquals( artifact.getClassifier(), translatedArtifact.getClassifier() ); - assertEquals( type, translatedArtifact.getExtension() ); + assertEquals(artifact.getClassifier(), translatedArtifact.getClassifier()); + assertEquals(type, translatedArtifact.getExtension()); found = true; break; } } - assertTrue( found ); + assertTrue(found); } } - public void testNullType() - { - doTestNullEmptyType( null ); + public void testNullType() { + doTestNullEmptyType(null); } - public void testEmptyType() - { - doTestNullEmptyType( "" ); + public void testEmptyType() { + doTestNullEmptyType(""); } - public void doTestNullEmptyType( String type ) - { + public void doTestNullEmptyType(String type) { String classifier = "jdk5"; - ArtifactTranslator at = new ClassifierTypeTranslator( artifactHandlerManager, classifier, type ); - Set results = at.translate( artifacts, log ); + ArtifactTranslator at = new ClassifierTypeTranslator(artifactHandlerManager, classifier, type); + Set results = at.translate(artifacts, log); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { Iterator resultIter = results.iterator(); boolean found = false; - while ( !found && resultIter.hasNext() ) - { + while (!found && resultIter.hasNext()) { ArtifactCoordinate translatedArtifact = resultIter.next(); - if ( artifact.getArtifactId() == translatedArtifact.getArtifactId() - && artifact.getGroupId() == translatedArtifact.getGroupId() - /* && artifact.getScope() == translatedArtifact.getScope() */ ) - { + if (artifact.getArtifactId() == translatedArtifact.getArtifactId() + && artifact.getGroupId() == translatedArtifact.getGroupId() + /* && artifact.getScope() == translatedArtifact.getScope() */ ) { // classifier is null, should be the same as the artifact - assertEquals( classifier, translatedArtifact.getClassifier() ); - assertEquals( artifact.getType(), translatedArtifact.getExtension() ); + assertEquals(classifier, translatedArtifact.getClassifier()); + assertEquals(artifact.getType(), translatedArtifact.getExtension()); found = true; break; } } - assertTrue( found ); + assertTrue(found); } } - public void testClassifierAndType() - { + public void testClassifierAndType() { String classifier = "jdk14"; String type = "sources"; - ArtifactTranslator at = new ClassifierTypeTranslator( artifactHandlerManager, classifier, type ); - Set results = at.translate( artifacts, log ); + ArtifactTranslator at = new ClassifierTypeTranslator(artifactHandlerManager, classifier, type); + Set results = at.translate(artifacts, log); - for ( Artifact artifact : artifacts ) - { + for (Artifact artifact : artifacts) { Iterator resultIter = results.iterator(); boolean found = false; - while ( !found && resultIter.hasNext() ) - { + while (!found && resultIter.hasNext()) { ArtifactCoordinate translatedArtifact = resultIter.next(); - if ( artifact.getArtifactId() == translatedArtifact.getArtifactId() - && artifact.getGroupId() == translatedArtifact.getGroupId() ) - { - assertEquals( translatedArtifact.getClassifier(), classifier ); - assertEquals( translatedArtifact.getExtension(), type ); + if (artifact.getArtifactId() == translatedArtifact.getArtifactId() + && artifact.getGroupId() == translatedArtifact.getGroupId()) { + assertEquals(translatedArtifact.getClassifier(), classifier); + assertEquals(translatedArtifact.getExtension(), type); found = true; break; } } - assertTrue( found ); + assertTrue(found); } } - public void testGetterSetter() - { + public void testGetterSetter() { String classifier = "class"; String type = "type"; - ClassifierTypeTranslator at = new ClassifierTypeTranslator( artifactHandlerManager, classifier, type ); - - assertEquals( classifier, at.getClassifier() ); - assertEquals( type, at.getType() ); + ClassifierTypeTranslator at = new ClassifierTypeTranslator(artifactHandlerManager, classifier, type); - at.setClassifier( type ); - at.setType( classifier ); + assertEquals(classifier, at.getClassifier()); + assertEquals(type, at.getType()); - assertEquals( type, at.getClassifier() ); - assertEquals( classifier, at.getType() ); + at.setClassifier(type); + at.setType(classifier); + assertEquals(type, at.getClassifier()); + assertEquals(classifier, at.getType()); } } diff --git a/src/test/resources/unit/build-classpath-test/plugin-config.xml b/src/test/resources/unit/build-classpath-test/plugin-config.xml index 29e4f6955..df85345b4 100644 --- a/src/test/resources/unit/build-classpath-test/plugin-config.xml +++ b/src/test/resources/unit/build-classpath-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/collect-test/plugin-config.xml b/src/test/resources/unit/collect-test/plugin-config.xml index 671a1656e..664fb38e9 100644 --- a/src/test/resources/unit/collect-test/plugin-config.xml +++ b/src/test/resources/unit/collect-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/copy-dependencies-test/plugin-config.xml b/src/test/resources/unit/copy-dependencies-test/plugin-config.xml index 4198fc70a..726aa2109 100644 --- a/src/test/resources/unit/copy-dependencies-test/plugin-config.xml +++ b/src/test/resources/unit/copy-dependencies-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/copy-test/plugin-config.xml b/src/test/resources/unit/copy-test/plugin-config.xml index 29e4f6955..df85345b4 100644 --- a/src/test/resources/unit/copy-test/plugin-config.xml +++ b/src/test/resources/unit/copy-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/get-test/plugin-config.xml b/src/test/resources/unit/get-test/plugin-config.xml index ce4a62595..45fab53aa 100644 --- a/src/test/resources/unit/get-test/plugin-config.xml +++ b/src/test/resources/unit/get-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/properties-test/plugin-config.xml b/src/test/resources/unit/properties-test/plugin-config.xml index dc313d7f1..60ef26f5d 100755 --- a/src/test/resources/unit/properties-test/plugin-config.xml +++ b/src/test/resources/unit/properties-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/resolve-test/plugin-config.xml b/src/test/resources/unit/resolve-test/plugin-config.xml index 29e4f6955..df85345b4 100644 --- a/src/test/resources/unit/resolve-test/plugin-config.xml +++ b/src/test/resources/unit/resolve-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/tree-test/plugin-config.xml b/src/test/resources/unit/tree-test/plugin-config.xml index 2766171f4..5d61ca75a 100644 --- a/src/test/resources/unit/tree-test/plugin-config.xml +++ b/src/test/resources/unit/tree-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/unpack-dependencies-test/plugin-config.xml b/src/test/resources/unit/unpack-dependencies-test/plugin-config.xml index 6cbb0e333..01a1f1904 100644 --- a/src/test/resources/unit/unpack-dependencies-test/plugin-config.xml +++ b/src/test/resources/unit/unpack-dependencies-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/unpack-dependencies-test/test.txt b/src/test/resources/unit/unpack-dependencies-test/test.txt index 9ea5c8a5c..4ee425451 100644 --- a/src/test/resources/unit/unpack-dependencies-test/test.txt +++ b/src/test/resources/unit/unpack-dependencies-test/test.txt @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an diff --git a/src/test/resources/unit/unpack-test/plugin-config.xml b/src/test/resources/unit/unpack-test/plugin-config.xml index 29e4f6955..df85345b4 100644 --- a/src/test/resources/unit/unpack-test/plugin-config.xml +++ b/src/test/resources/unit/unpack-test/plugin-config.xml @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an