<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTest.java<|end_filename|>
package org.apache.maven.plugins.dependency;

/*
 * 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 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;

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 );

    private ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class );

    private ArrayList<ArtifactRepository> artifactRepos = new ArrayList<>();

    private ArrayList<ArtifactRepository> pluginRepos = new ArrayList<>();

    static class ConcreteDependencyMojo extends AbstractDependencyMojo
    {
        static ConcreteDependencyMojo createConcreteDependencyMojoWithArtifactRepositories(
                MavenSession mavenSession, List<ArtifactRepository> artifactRepos )
                throws NoSuchFieldException, IllegalAccessException
        {
            ConcreteDependencyMojo cdm = new ConcreteDependencyMojo();
            cdm.session = mavenSession;

            Field par = AbstractDependencyMojo.class.getDeclaredField( "remoteRepositories" );
            par.setAccessible( true );
            par.set( cdm, artifactRepos );

            return cdm;
        }

        static ConcreteDependencyMojo createConcreteDependencyMojoWithPluginRepositories(
                MavenSession mavenSession, List<ArtifactRepository> pluginRepos )
                throws NoSuchFieldException, IllegalAccessException
        {
            ConcreteDependencyMojo cdm = new ConcreteDependencyMojo();
            cdm.session = mavenSession;

            Field par = AbstractDependencyMojo.class.getDeclaredField( "remotePluginRepositories" );
            par.setAccessible( true );
            par.set( cdm, pluginRepos );

            return cdm;
        }

        @Override
        protected void doExecute()
        {
        }
    }

    @Override
    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" ) );

        when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest );
    }

    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 );

        ProjectBuildingRequest pbr = mojo.newResolveArtifactProjectBuildingRequest();
        List<ArtifactRepository> rrepos = pbr.getRemoteRepositories();

        assertEquals( 3, rrepos.size() );
    }

    public void testNewResolveArtifactProjectBuildingRequestRemoteRepositoriesContents()
            throws NoSuchFieldException, IllegalAccessException
    {
        AbstractDependencyMojo mojo = createConcreteDependencyMojoWithArtifactRepositories( session, artifactRepos );

        ProjectBuildingRequest pbr = mojo.newResolveArtifactProjectBuildingRequest();
        List<ArtifactRepository> rrepos = pbr.getRemoteRepositories();

        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 );

        ProjectBuildingRequest pbr = mojo.newResolvePluginProjectBuildingRequest();
        List<ArtifactRepository> rrepos = pbr.getRemoteRepositories();

        assertEquals( 2, rrepos.size() );
    }

    public void testNewResolvePluginProjectBuildingRequestRemoteRepositoriesContents()
            throws NoSuchFieldException, IllegalAccessException
    {
        AbstractDependencyMojo mojo = createConcreteDependencyMojoWithPluginRepositories( session, pluginRepos );

        ProjectBuildingRequest pbr = mojo.newResolvePluginProjectBuildingRequest();
        List<ArtifactRepository> rrepos = pbr.getRemoteRepositories();

        assertEquals( "pr-central", rrepos.get( 0 ).getId() );
        assertEquals( "pr-plugins", rrepos.get( 1 ).getId() );
    }
}

<|start_filename|>src/main/java/org/apache/maven/plugins/dependency/resolvers/CollectDependenciesMojo.java<|end_filename|>
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.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;

/**
 * <p>
 * Goal that collects the project dependencies from the repository. This goal requires Maven 3.0 or higher to function
 * because it uses "requiresDependencyCollection". This means that it lists the groupId:artifactId:version information
 * by downloading the pom files without downloading the actual artifacts such as jar files.
 * </p>
 * <p>
 * This is very useful when full dependency resolution might fail due to projects which haven't been built yet.
 * </p>
 * <p>
 * It is identical to {@link ResolveDependenciesMojo} except for using the requiresDependencyCollection annotation
 * attribute instead of requiresDependencyResolution.
 * </p>
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @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
{
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/TestSkip.java<|end_filename|>
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
 * 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.
 */

public class TestSkip
    extends AbstractDependencyMojoTestCase
{
    public void testSkipAnalyze()
        throws Exception
    {
        doTest( "analyze" );
    }

    public void testSkipAnalyzeDepMgt()
        throws Exception
    {
        doTest( "analyze-dep-mgt" );
    }

    public void testSkipAnalyzeOnly()
        throws Exception
    {
        doTest( "analyze-only" );
    }

    public void testSkipAnalyzeReport()
        throws Exception
    {
        doSpecialTest( "analyze-report" );
    }

    public void testSkipAnalyzeDuplicate()
        throws Exception
    {
        doTest( "analyze-duplicate" );
    }

    public void testSkipBuildClasspath()
        throws Exception
    {
        doTest( "build-classpath" );
    }

    public void testSkipCopy()
        throws Exception
    {
        doTest( "copy" );
    }

    public void testSkipCopyDependencies()
        throws Exception
    {
        doTest( "copy-dependencies" );
    }

    public void testSkipGet()
        throws Exception
    {
        doSpecialTest( "get" );
    }

    public void testSkipGoOffline()
        throws Exception
    {
        doTest( "go-offline" );
    }

    public void testSkipList()
        throws Exception
    {
        doTest( "list" );
    }

    public void testSkipProperties()
        throws Exception
    {
        doTest( "properties" );
    }

    public void testSkipPurgeLocalRepository()
        throws Exception
    {
        doSpecialTest( "purge-local-repository" );
    }

    public void testSkipResolve()
        throws Exception
    {
        doTest( "resolve" );
    }

    public void testSkipResolvePlugins()
        throws Exception
    {
        doTest( "resolve-plugins" );
    }

    public void testSkipSources()
        throws Exception
    {
        doTest( "sources" );
    }

    public void testSkipTree()
        throws Exception
    {
        doTest( "tree" );
    }

    public void testSkipUnpack()
        throws Exception
    {
        doTest( "unpack" );
    }

    public void testSkipUnpackDependencies()
        throws Exception
    {
        doTest( "unpack-dependencies" );
    }

    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" );
    }

    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<String> captor = ArgumentCaptor.forClass( String.class );
        verify( log, atLeastOnce() ).info( captor.capture() );
        assertTrue( captor.getValue().contains( "Skipping plugin execution" ) );
    }

}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/TestListClassesMojo.java<|end_filename|>
package org.apache.maven.plugins.dependency;

/*
 * 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.execution.MavenSession;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;

import java.io.File;

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" );

        assertTrue( testPom.exists() );
        mojo = (ListClassesMojo) lookupMojo( "list-classes", testPom );

        assertNotNull( mojo );

        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( "<PASSWORD>" );
        settings.addServer( server );
        legacySupport.setSession( session );

        installLocalRepository( legacySupport );

        setVariableValueToObject( mojo, "session", legacySupport.getSession() );
    }
    
    public void testListClassesNotTransitive()
            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" );
        setVariableValueToObject( mojo, "artifact", "org.apache.commons:commons-lang3:3.6" );
        setVariableValueToObject( mojo, "transitive", Boolean.FALSE );

        mojo.execute();
    }

    public void testListClassesTransitive()
            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" );
        setVariableValueToObject( mojo, "artifact", "org.apache.commons:commons-lang3:3.6" );
        setVariableValueToObject( mojo, "transitive", Boolean.TRUE );

        mojo.execute();
    }
}


<|start_filename|>src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportMojo.java<|end_filename|>
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
 * 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.doxia.sink.Sink;
import org.apache.maven.doxia.siterenderer.Renderer;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Execute;
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.project.MavenProject;
import org.apache.maven.reporting.AbstractMavenReport;
import org.apache.maven.reporting.MavenReportException;
import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalysis;
import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalyzer;
import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalyzerException;

import java.io.File;
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
{
    // fields -----------------------------------------------------------------

    /**
     * The Maven project to analyze.
     */
    @Parameter( defaultValue = "${project}", readonly = true, required = true )
    private MavenProject project;

    /**
     * The Maven project dependency analyzer to use.
     */
    @Component
    private ProjectDependencyAnalyzer analyzer;

    /**
     *
     */
    @Component
    private Renderer siteRenderer;

    /**
     * Target folder
     *
     * @since 2.0-alpha-5
     */
    @Parameter( defaultValue = "${project.build.directory}", readonly = true )
    private File outputDirectory;

    /**
     * Ignore Runtime/Provided/Test/System scopes for unused dependency analysis
     * 
     * @since 2.2
     */
    @Parameter( property = "ignoreNonCompile", defaultValue = "false" )
    private boolean ignoreNonCompile;

    /**
     * Force dependencies as used, to override incomplete result caused by bytecode-level analysis. Dependency format is
     * <code>groupId:artifactId</code>.
     * 
     * @since 2.6
     */
    @Parameter
    private String[] usedDependencies;

    /**
     * Skip plugin execution completely.
     *
     * @since 2.7
     */
    @Parameter( property = "mdep.analyze.skip", defaultValue = "false" )
    private boolean skip;

    // Mojo methods -----------------------------------------------------------

    /*
     * @see org.apache.maven.plugin.Mojo#execute()
     */
    @Override
    public void executeReport( Locale locale )
        throws MavenReportException
    {
        if ( skip )
        {
            getLog().info( "Skipping plugin execution" );
            return;
        }

        // Step 0: Checking pom availability
        if ( "pom".equals( project.getPackaging() ) )
        {
            getLog().info( "Skipping pom project" );
            return;
        }

        if ( outputDirectory == null || !outputDirectory.exists() )
        {
            getLog().info( "Skipping project with no Target directory" );
            return;
        }

        // Step 1: Analyze the project
        ProjectDependencyAnalysis analysis;
        try
        {
            analysis = analyzer.analyze( project );

            if ( usedDependencies != null )
            {
                analysis = analysis.forceDeclaredDependenciesUsage( usedDependencies );
            }
        }
        catch ( ProjectDependencyAnalyzerException exception )
        {
            throw new MavenReportException( "Cannot analyze dependencies", exception );
        }

        // remove everything that's not in the compile scope
        if ( ignoreNonCompile )
        {
            analysis = analysis.ignoreNonCompile();
        }

        // Step 2: Create sink and bundle
        Sink sink = getSink();
        ResourceBundle bundle = getBundle( locale );

        // Step 3: Generate the report
        AnalyzeReportView analyzethis = new AnalyzeReportView();
        analyzethis.generateReport( analysis, sink, bundle );
    }

    // MavenReport methods ----------------------------------------------------

    /*
     * @see org.apache.maven.reporting.AbstractMavenReport#getOutputName()
     */
    @Override
    public String getOutputName()
    {
        return "dependency-analysis";
    }

    /*
     * @see org.apache.maven.reporting.AbstractMavenReport#getName(java.util.Locale)
     */
    @Override
    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" );
    }

    // AbstractMavenReport methods --------------------------------------------

    /*
     * @see org.apache.maven.reporting.AbstractMavenReport#getProject()
     */
    @Override
    protected MavenProject getProject()
    {
        return project;
    }

    /*
     * @see org.apache.maven.reporting.AbstractMavenReport#getOutputDirectory()
     */
    @Override
    protected String getOutputDirectory()
    {
        getLog().info( outputDirectory.toString() );

        return outputDirectory.toString();
    }

    /*
     * @see org.apache.maven.reporting.AbstractMavenReport#getSiteRenderer()
     */
    @Override
    protected Renderer getSiteRenderer()
    {
        return siteRenderer;
    }

    // protected methods ------------------------------------------------------

    /**
     * @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() );
    }
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyProjectStub.java<|end_filename|>
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
 * 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.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
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;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Build;
import org.apache.maven.model.CiManagement;
import org.apache.maven.model.Contributor;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.Developer;
import org.apache.maven.model.DistributionManagement;
import org.apache.maven.model.Extension;
import org.apache.maven.model.IssueManagement;
import org.apache.maven.model.License;
import org.apache.maven.model.MailingList;
import org.apache.maven.model.Model;
import org.apache.maven.model.Organization;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.Prerequisites;
import org.apache.maven.model.Profile;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.model.Reporting;
import org.apache.maven.model.Repository;
import org.apache.maven.model.Resource;
import org.apache.maven.model.Scm;
import org.apache.maven.plugin.testing.stubs.DefaultArtifactHandlerStub;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.artifact.InvalidDependencyVersionException;
import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.util.xml.Xpp3Dom;

/**
 * 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
{
    private String groupId;

    private String artifactId;

    private String name;

    private Model model;

    private MavenProject parent;

    private List<Dependency> dependencies;

    private File file;

    private List<MavenProject> collectedProjects;

    private List<Artifact> attachedArtifacts;

    private List<String> compileSourceRoots;

    private List<String> testCompileSourceRoots;

    private List<String> scriptSourceRoots;

    private List<ArtifactRepository> pluginArtifactRepositories;

    private List<Profile> activeProfiles;

    private Set<Artifact> dependencyArtifacts;

    private DependencyManagement dependencyManagement;

    private Artifact artifact;

    private Model originalModel;

    private boolean executionRoot;

    private List<Artifact> compileArtifacts;

    private List<Dependency> compileDependencies;

    private List<Dependency> systemDependencies;

    private List<String> testClasspathElements;

    private List<Dependency> testDependencies;

    private List<String> systemClasspathElements;

    private List<Artifact> systemArtifacts;

    private List<Artifact> testArtifacts;

    private List<Artifact> runtimeArtifacts;

    private List<Dependency> runtimeDependencies;

    private List<String> runtimeClasspathElements;

    private String modelVersion;

    private String packaging;

    private String inceptionYear;

    private String url;

    private String description;

    private String version;

    private String defaultGoal;

    private Set<Artifact> artifacts;

    private Properties properties;

    public DependencyProjectStub()
    {
        super( (Model) null );
    }

    // kinda dangerous...
    public DependencyProjectStub( Model model )
    {
        // super(model);
        super( (Model) null );
    }

    // kinda dangerous...
    public DependencyProjectStub( MavenProject project )
    {
        // super(project);
        super( (Model) null );
    }

    public String getModulePathAdjustment( MavenProject mavenProject )
        throws IOException
    {
        return "";
    }

    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 );
        }
        return artifact;
    }

    public void setArtifact( Artifact artifact )
    {
        this.artifact = artifact;
    }

    public Model getModel()
    {
        return model;
    }

    public MavenProject getParent()
    {
        return parent;
    }

    public void setParent( MavenProject mavenProject )
    {
        this.parent = mavenProject;
    }

    public void setRemoteArtifactRepositories( List<ArtifactRepository> list )
    {

    }

    public List<ArtifactRepository> getRemoteArtifactRepositories()
    {
        return Collections.emptyList();
    }

    public boolean hasParent()
    {
        return ( parent != null );
    }

    public File getFile()
    {
        return file;
    }

    public void setFile( File file )
    {
        this.file = file;
    }

    public File getBasedir()
    {
        return new File( PlexusTestCase.getBasedir() );
    }

    public void setDependencies( List<Dependency> list )
    {
        dependencies = list;
    }

    public List<Dependency> getDependencies()
    {
        if ( dependencies == null )
        {
            dependencies = Collections.emptyList();
        }
        return dependencies;
    }

    public void setDependencyManagement( DependencyManagement depMgt )
    {
        this.dependencyManagement = depMgt;
    }

    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 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 List<String> getCompileSourceRoots()
    {
        return compileSourceRoots;
    }

    public List<String> getScriptSourceRoots()
    {
        return scriptSourceRoots;
    }

    public List<String> getTestCompileSourceRoots()
    {
        return testCompileSourceRoots;
    }

    public List<String> getCompileClasspathElements()
        throws DependencyResolutionRequiredException
    {
        return compileSourceRoots;
    }

    public void setCompileArtifacts( List<Artifact> compileArtifacts )
    {
        this.compileArtifacts = compileArtifacts;
    }

    public List<Artifact> getCompileArtifacts()
    {
        return compileArtifacts;
    }

    public List<Dependency> getCompileDependencies()
    {
        return compileDependencies;
    }

    public List<String> getTestClasspathElements()
        throws DependencyResolutionRequiredException
    {
        return testClasspathElements;
    }

    public List<Artifact> getTestArtifacts()
    {
        return testArtifacts;
    }

    public List<Dependency> getTestDependencies()
    {
        return testDependencies;
    }

    public List<String> getRuntimeClasspathElements()
        throws DependencyResolutionRequiredException
    {
        return runtimeClasspathElements;
    }

    public List<Artifact> getRuntimeArtifacts()
    {
        return runtimeArtifacts;
    }

    public List<Dependency> getRuntimeDependencies()
    {
        return runtimeDependencies;
    }

    public List<String> getSystemClasspathElements()
        throws DependencyResolutionRequiredException
    {
        return systemClasspathElements;
    }

    public List<Artifact> getSystemArtifacts()
    {
        return systemArtifacts;
    }

    public void setRuntimeClasspathElements( List<String> runtimeClasspathElements )
    {
        this.runtimeClasspathElements = runtimeClasspathElements;
    }

    public void setAttachedArtifacts( List<Artifact> attachedArtifacts )
    {
        this.attachedArtifacts = attachedArtifacts;
    }

    public void setCompileSourceRoots( List<String> compileSourceRoots )
    {
        this.compileSourceRoots = compileSourceRoots;
    }

    public void setTestCompileSourceRoots( List<String> testCompileSourceRoots )
    {
        this.testCompileSourceRoots = testCompileSourceRoots;
    }

    public void setScriptSourceRoots( List<String> scriptSourceRoots )
    {
        this.scriptSourceRoots = scriptSourceRoots;
    }

    public void setCompileDependencies( List<Dependency> compileDependencies )
    {
        this.compileDependencies = compileDependencies;
    }

    public void setSystemDependencies( List<Dependency> systemDependencies )
    {
        this.systemDependencies = systemDependencies;
    }

    public void setTestClasspathElements( List<String> testClasspathElements )
    {
        this.testClasspathElements = testClasspathElements;
    }

    public void setTestDependencies( List<Dependency> testDependencies )
    {
        this.testDependencies = testDependencies;
    }

    public void setSystemClasspathElements( List<String> systemClasspathElements )
    {
        this.systemClasspathElements = systemClasspathElements;
    }

    public void setSystemArtifacts( List<Artifact> systemArtifacts )
    {
        this.systemArtifacts = systemArtifacts;
    }

    public void setTestArtifacts( List<Artifact> testArtifacts )
    {
        this.testArtifacts = testArtifacts;
    }

    public void setRuntimeArtifacts( List<Artifact> runtimeArtifacts )
    {
        this.runtimeArtifacts = runtimeArtifacts;
    }

    public void setRuntimeDependencies( List<Dependency> runtimeDependencies )
    {
        this.runtimeDependencies = runtimeDependencies;
    }

    public void setModel( Model model )
    {
        this.model = model;
    }

    public List<Dependency> getSystemDependencies()
    {
        return systemDependencies;
    }

    public void setModelVersion( String string )
    {
        this.modelVersion = string;
    }

    public String getModelVersion()
    {
        return modelVersion;
    }

    public String getId()
    {
        return "";
    }

    public void setGroupId( String string )
    {
        this.groupId = string;
    }

    public String getGroupId()
    {
        return groupId;
    }

    public void setArtifactId( String string )
    {
        this.artifactId = string;
    }

    public String getArtifactId()
    {
        return artifactId;
    }

    public void setName( String string )
    {
        this.name = string;
    }

    public String getName()
    {
        return name;
    }

    public void setVersion( String string )
    {
        this.version = string;
    }

    public String getVersion()
    {
        return version;
    }

    public String getPackaging()
    {
        return packaging;
    }

    public void setPackaging( String string )
    {
        this.packaging = string;
    }

    public void setInceptionYear( String string )
    {
        this.inceptionYear = string;
    }

    public String getInceptionYear()
    {
        return inceptionYear;
    }

    public void setUrl( String string )
    {
        this.url = string;
    }

    public String getUrl()
    {
        return url;
    }

    public Prerequisites getPrerequisites()
    {
        return null;
    }

    public void setIssueManagement( IssueManagement issueManagement )
    {

    }

    public CiManagement getCiManagement()
    {
        return null;
    }

    public void setCiManagement( CiManagement ciManagement )
    {

    }

    public IssueManagement getIssueManagement()
    {
        return null;
    }

    public void setDistributionManagement( DistributionManagement distributionManagement )
    {

    }

    public DistributionManagement getDistributionManagement()
    {
        return null;
    }

    public void setDescription( String string )
    {
        this.description = string;
    }

    public String getDescription()
    {
        return description;
    }

    public void setOrganization( Organization organization )
    {

    }

    public Organization getOrganization()
    {
        return null;
    }

    public void setScm( Scm scm )
    {

    }

    public Scm getScm()
    {
        return null;
    }

    @Override
    public void setMailingLists( List<MailingList> list )
    {

    }

    public List<MailingList> getMailingLists()
    {
        return Collections.emptyList();
    }

    public void addMailingList( MailingList mailingList )
    {

    }

    @Override
    public void setDevelopers( List<Developer> list )
    {

    }

    public List<Developer> getDevelopers()
    {
        return Collections.emptyList();
    }

    public void addDeveloper( Developer developer )
    {

    }

    public void setContributors( List<Contributor> list )
    {

    }

    public List<Contributor> getContributors()
    {
        return Collections.emptyList();
    }

    public void addContributor( Contributor contributor )
    {

    }

    public void setBuild( Build build )
    {

    }

    public Build getBuild()
    {
        return null;
    }

    public List<Resource> getResources()
    {
        return Collections.emptyList();
    }

    public List<Resource> getTestResources()
    {
        return Collections.emptyList();
    }

    public void addResource( Resource resource )
    {

    }

    public void addTestResource( Resource resource )
    {

    }

    public void setReporting( Reporting reporting )
    {

    }

    public Reporting getReporting()
    {
        return null;
    }

    public void setLicenses( List<License> list )
    {

    }

    public List<License> getLicenses()
    {
        return Collections.emptyList();
    }

    public void addLicense( License license )
    {

    }

    public void setArtifacts( Set<Artifact> set )
    {
        this.artifacts = set;
    }

    public Set<Artifact> getArtifacts()
    {
        if ( artifacts == null )
        {
            return Collections.emptySet();
        }
        else
        {
            return artifacts;
        }
    }

    public Map<String, Artifact> getArtifactMap()
    {
        return Collections.emptyMap();
    }

    public void setPluginArtifacts( Set<Artifact> set )
    {

    }

    public Set<Artifact> getPluginArtifacts()
    {
        return Collections.emptySet();
    }

    public Map<String, Artifact> getPluginArtifactMap()
    {
        return Collections.emptyMap();
    }

    public void setReportArtifacts( Set<Artifact> set )
    {

    }

    public Set<Artifact> getReportArtifacts()
    {
        return Collections.emptySet();
    }

    public Map<String, Artifact> getReportArtifactMap()
    {
        return Collections.emptyMap();
    }

    public void setExtensionArtifacts( Set<Artifact> set )
    {

    }

    public Set<Artifact> getExtensionArtifacts()
    {
        return Collections.emptySet();
    }

    public Map<String, Artifact> getExtensionArtifactMap()
    {
        return Collections.emptyMap();
    }

    public void setParentArtifact( Artifact artifact )
    {

    }

    public Artifact getParentArtifact()
    {
        return null;
    }

    public List<Repository> getRepositories()
    {
        return Collections.emptyList();
    }

    public List<ReportPlugin> getReportPlugins()
    {
        return Collections.emptyList();
    }

    public List<Plugin> getBuildPlugins()
    {
        return Collections.emptyList();
    }

    public List<String> getModules()
    {
        return Collections.singletonList( "" );
    }

    public PluginManagement getPluginManagement()
    {
        return null;
    }

    public void addPlugin( Plugin plugin )
    {

    }

    public void injectPluginManagementInfo( Plugin plugin )
    {

    }

    public List<MavenProject> getCollectedProjects()
    {
        return collectedProjects;
    }

    public void setCollectedProjects( List<MavenProject> list )
    {
        this.collectedProjects = list;
    }

    public void setPluginArtifactRepositories( List<ArtifactRepository> list )
    {
        this.pluginArtifactRepositories = list;
    }

    public List<ArtifactRepository> getPluginArtifactRepositories()
    {
        return pluginArtifactRepositories;
    }

    public ArtifactRepository getDistributionManagementArtifactRepository()
    {
        return null;
    }

    public List<Repository> getPluginRepositories()
    {
        return Collections.emptyList();
    }

    public void setActiveProfiles( List<Profile> list )
    {
        activeProfiles = list;
    }

    public List<Profile> getActiveProfiles()
    {
        return activeProfiles;
    }

    public void addAttachedArtifact( Artifact theArtifact )
    {
        if ( attachedArtifacts == null )
        {
            this.attachedArtifacts = Collections.singletonList( theArtifact );
        }
        else
        {
            attachedArtifacts.add( theArtifact );
        }
    }

    public List<Artifact> getAttachedArtifacts()
    {
        return attachedArtifacts;
    }

    public Xpp3Dom getGoalConfiguration( String string, String string1, String string2, String string3 )
    {
        return null;
    }

    public Xpp3Dom getReportConfiguration( String string, String string1, String string2 )
    {
        return null;
    }

    public MavenProject getExecutionProject()
    {
        return null;
    }

    public void setExecutionProject( MavenProject mavenProject )
    {

    }

    public void writeModel( Writer writer )
        throws IOException
    {

    }

    public void writeOriginalModel( Writer writer )
        throws IOException
    {

    }

    public Set<Artifact> getDependencyArtifacts()
    {
        return dependencyArtifacts;
    }

    public void setDependencyArtifacts( Set<Artifact> set )
    {
        this.dependencyArtifacts = set;
    }

    public void setReleaseArtifactRepository( ArtifactRepository artifactRepository )
    {
        // this.releaseArtifactRepository = artifactRepository;
    }

    public void setSnapshotArtifactRepository( ArtifactRepository artifactRepository )
    {
        // this.snapshotArtifactRepository = artifactRepository;
    }

    public void setOriginalModel( Model model )
    {
        this.originalModel = model;
    }

    public Model getOriginalModel()
    {
        return originalModel;
    }

    public List<Extension> getBuildExtensions()
    {
        return Collections.emptyList();
    }

    @Override
    public Set<Artifact> createArtifacts( ArtifactFactory artifactFactory, String string, ArtifactFilter artifactFilter )
        throws InvalidDependencyVersionException
    {
        return Collections.emptySet();
    }

    public void addProjectReference( MavenProject mavenProject )
    {

    }

    public void attachArtifact( String string, String string1, File theFile )
    {

    }

    public Properties getProperties()
    {
        if ( properties == null )
        {
            properties = new Properties();
        }
        return properties;
    }

    public List<String> getFilters()
    {
        return Collections.singletonList( "" );
    }

    public Map<String, MavenProject> getProjectReferences()
    {
        return Collections.emptyMap();
    }

    public boolean isExecutionRoot()
    {
        return executionRoot;
    }

    public void setExecutionRoot( boolean b )
    {
        this.executionRoot = b;
    }

    public String getDefaultGoal()
    {
        return defaultGoal;
    }

    public Artifact replaceWithActiveArtifact( Artifact theArtifact )
    {
        return null;
    }
}


<|start_filename|>src/main/java/org/apache/maven/plugins/dependency/DisplayAncestorsMojo.java<|end_filename|>
package org.apache.maven.plugins.dependency;

/*
 * 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.commons.lang3.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
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.project.MavenProject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Displays all ancestor POMs of the project. This may be useful in a continuous integration system where you want to
 * know all parent poms of the project.
 *
 * @author <NAME>
 * @since 2.9
 */
@Mojo( name = "display-ancestors", threadSafe = true, requiresProject = true, defaultPhase = LifecyclePhase.VALIDATE )
public class DisplayAncestorsMojo
    extends AbstractMojo
{

    /**
     * POM
     */
    @Parameter( defaultValue = "${project}", readonly = true )
    private MavenProject project;

    @Override
    public void execute()
        throws MojoExecutionException, MojoFailureException
    {
        final List<String> ancestors = collectAncestors();

        if ( ancestors.isEmpty() )
        {
            getLog().info( "No Ancestor POMs!" );
        }
        else
        {
            getLog().info( String.format( Locale.US, "Ancestor POMs: %s", StringUtils.join( ancestors, " <- " ) ) );
        }

    }

    private ArrayList<String> collectAncestors()
    {
        final ArrayList<String> 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() );

            ancestors.add( gav );

            currentAncestor = currentAncestor.getParent();
        }

        return ancestors;
    }

}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/utils/markers/TestDefaultMarkerFileHandler.java<|end_filename|>
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
 * 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.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;
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.StubDefaultFileMarkerHandler;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.testing.SilentLog;

/**
 * @author brianf
 */
public class TestDefaultMarkerFileHandler
    extends TestCase
{
    List<Artifact> artifacts = new ArrayList<>();

    Log log = new SilentLog();

    File outputFolder;

    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() );
    }

    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() );
        handler.setMarker();
        assertTrue( handler.isMarkerSet() );
        handler.clearMarker();
        assertFalse( handler.isMarkerSet() );

        handler.setMarker();
        assertTrue( handler.isMarkerSet() );
        handler.setMarker();
        assertTrue( handler.isMarkerSet() );

        handler.clearMarker();
        assertFalse( handler.isMarkerSet() );
        handler.clearMarker();
        assertFalse( handler.isMarkerSet() );
    }

    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() );

        handler.setMarker();
        assertTrue( handler.isMarkerSet() );
        assertTrue( handle.exists() );

        handle.delete();
        assertFalse( handler.isMarkerSet() );

        handle.createNewFile();
        assertTrue( handler.isMarkerSet() );

        handler.clearMarker();
        assertFalse( handle.exists() );
    }

    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() );
        // if the marker is not set, assume it is infinately older than the
        // artifact.
        assertTrue( handler.isMarkerOlder( theArtifact ) );
        handler.setMarker();
        assertFalse( handler.isMarkerOlder( theArtifact ) );

        assertTrue( theFile.setLastModified( theFile.lastModified() + 60000 ) );
        assertTrue( handler.isMarkerOlder( theArtifact ) );

        theFile.delete();
        handler.clearMarker();
        assertFalse( handler.isMarkerSet() );
    }

    public void testMarkerFileException()
    {
        // this stub wraps the file with an object to throw exceptions
        StubDefaultFileMarkerHandler handler =
            new StubDefaultFileMarkerHandler( artifacts.get( 0 ), this.outputFolder );
        try
        {
            handler.setMarker();
            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() );

        assertNull( handler.getMarkerFilesDirectory() );
        handler.setMarkerFilesDirectory( outputFolder );
        assertSame( outputFolder, handler.getMarkerFilesDirectory() );
    }

    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 ) );
        handler.setMarker();
        assertTrue( handler.isMarkerSet() );
        handler.clearMarker();
        assertFalse( handler.isMarkerSet() );
    }
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DuplicateDependencies2ProjectStub.java<|end_filename|>
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
 * 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.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;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

/**
 * 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" );
        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 );
        }

    }

    /**
     * @see org.apache.maven.plugin.testing.stubs.MavenProjectStub#getBasedir()
     */
    public File getBasedir()
    {
        return new File( super.getBasedir() + "/src/test/resources/unit/duplicate-dependencies" );
    }
}


<|start_filename|>src/main/java/org/apache/maven/plugins/dependency/resolvers/ExcludeReactorProjectsArtifactFilter.java<|end_filename|>
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.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
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 <NAME>
 */
public class ExcludeReactorProjectsArtifactFilter extends AbstractArtifactsFilter
{
    private final Log log;
    private final Set<String> reactorArtifactKeys;

    public ExcludeReactorProjectsArtifactFilter( final List<MavenProject> 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() ) );
        }
    }

    @Override
    public Set<Artifact> filter( final Set<Artifact> artifacts ) throws ArtifactFilterException
    {
        final Set<Artifact> 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" );
                }
            }
        }

        return results;
    }

    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 ) )
            {
                return true;
            }
        }
        return false;
    }
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java<|end_filename|>
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
 * 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.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;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase;
import org.apache.maven.plugins.dependency.utils.DependencyUtil;
import org.apache.maven.project.MavenProject;

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<ArtifactItem> 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" );

        List<ArtifactItem> list = new ArrayList<>( 1 );
        list.add( createArtifact( item ) );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        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() );
    }

    public void assertFilesExist( Collection<ArtifactItem> 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 testMojoDefaults()
    {
        CopyMojo themojo = new CopyMojo();

        assertFalse( themojo.isStripVersion() );
        assertFalse( themojo.isSkip() );
        assertFalse( themojo.isStripClassifier() );
    }

    public void testCopyFile()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        mojo.execute();

        assertFilesExist( list, true );
    }

    public void testCopyFileWithBaseVersion()
        throws Exception
    {
        List<ArtifactItem> 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 );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );
        mojo.setUseBaseVersion( true );

        mojo.execute();

        assertFilesExist( list, true );
    }

    public void testSkip()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );

        mojo.setSkip( true );
        mojo.setArtifactItems( list );

        mojo.execute();
        for ( ArtifactItem item : list )
        {
            // these will be null because no processing has occured only when everything is skipped
            assertNull( item.getOutputDirectory() );
            assertNull( item.getDestFileName() );
        }

    }

    public void testCopyFileNoOverwrite()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );

        for ( ArtifactItem item : list )
        {
            // make sure that we copy even if false is set - MDEP-80
            item.setOverWrite( "false" );
        }

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );
        mojo.execute();

        assertFilesExist( list, true );
    }

    public void testCopyToLocation()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );
        ArtifactItem item = list.get( 0 );
        item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        mojo.execute();

        assertFilesExist( list, true );
    }

    public void testCopyStripVersionSetInMojo()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );

        ArtifactItem item = list.get( 0 );
        item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) );
        mojo.setStripVersion( true );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        mojo.execute();
        assertEquals( DependencyUtil.getFormattedFileName( item.getArtifact(), true ), item.getDestFileName() );

        assertFilesExist( list, true );
    }

    public void testCopyStripClassifierSetInMojo()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );

        ArtifactItem item = list.get( 0 );
        item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) );
        mojo.setStripClassifier( true );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        mojo.execute();
        assertEquals( DependencyUtil.getFormattedFileName( item.getArtifact(), false, false, false, true ),
                      item.getDestFileName() );

        assertFilesExist( list, true );
    }

    public void testNonClassifierStrip()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getReleaseAndSnapshotArtifacts() );
        mojo.setStripVersion( true );
        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        mojo.execute();

        assertFilesExist( list, true );
    }

    public void testNonClassifierNoStrip()
        throws Exception
    {
        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getReleaseAndSnapshotArtifacts() );

        mojo.setArtifactItems( createArtifactItemArtifacts( list ) );

        mojo.execute();

        assertFilesExist( list, true );
    }

    public void testMissingVersionNotFound()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );
        mojo.setArtifactItems( list );

        try
        {
            mojo.execute();
            fail( "Expected Exception Here." );
        }
        catch ( MojoExecutionException e )
        {
            // caught the expected exception.
        }
    }

    public List<Dependency> 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" );

        Dependency dep2 = new Dependency();
        dep2.setArtifactId( item.getArtifactId() );
        dep2.setClassifier( "classifier" );
        dep2.setGroupId( item.getGroupId() );
        dep2.setType( item.getType() );
        dep2.setVersion( "2.1" );

        List<Dependency> list = new ArrayList<>( 2 );
        list.add( dep2 );
        list.add( dep );

        return list;
    }

    public void testMissingVersionFromDependencies()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );
        mojo.setArtifactItems( list );

        MavenProject project = mojo.getProject();
        project.setDependencies( createDependencyArtifacts( getDependencyList( item ) ) );

        mojo.execute();
        this.assertFileExists( item, true );
        assertEquals( "2.0-SNAPSHOT", item.getVersion() );
    }

    public void testMissingVersionFromDependenciesLooseMatch()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        MavenProject project = mojo.getProject();
        project.setDependencies( createDependencyArtifacts( getDependencyList( item ) ) );

        // ensure dependency exists
        item.setClassifier( "sources" );
        item.setType( "jar" );

        // pre-create item
        item.setVersion( "2.1" );
        createArtifact( item );
        item.setVersion( null );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );
        mojo.setArtifactItems( list );

        mojo.execute();
        this.assertFileExists( item, true );
        assertEquals( "2.1", item.getVersion() );
    }

    public void testMissingVersionFromDependenciesWithClassifier()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "classifier" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );
        mojo.setArtifactItems( list );

        MavenProject project = mojo.getProject();
        project.setDependencies( createDependencyArtifacts( getDependencyList( item ) ) );

        mojo.execute();
        this.assertFileExists( item, true );
        assertEquals( "2.1", item.getVersion() );
    }

    public List<Dependency> 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" );

        Dependency dep2 = new Dependency();
        dep2.setArtifactId( item.getArtifactId() );
        dep2.setClassifier( "classifier" );
        dep2.setGroupId( item.getGroupId() );
        dep2.setType( item.getType() );
        dep2.setVersion( "3.1" );

        List<Dependency> list = new ArrayList<>( 2 );
        list.add( dep2 );
        list.add( dep );

        return list;
    }

    public void testMissingVersionFromDependencyMgt()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        MavenProject project = mojo.getProject();
        project.setDependencies( getDependencyList( item ) );

        item = new ArtifactItem();

        item.setArtifactId( "artifactId-2" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );

        mojo.setArtifactItems( list );

        project.getDependencyManagement().setDependencies( createDependencyArtifacts( getDependencyMgtList( item ) ) );

        mojo.execute();

        this.assertFileExists( item, true );
        assertEquals( "3.0-SNAPSHOT", item.getVersion() );
    }

    public void testMissingVersionFromDependencyMgtLooseMatch()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        MavenProject project = mojo.getProject();
        project.setDependencies( getDependencyList( item ) );

        item = new ArtifactItem();

        item.setArtifactId( "artifactId-2" );
        item.setClassifier( "" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );

        mojo.setArtifactItems( list );

        project.getDependencyManagement().setDependencies( createDependencyArtifacts( getDependencyMgtList( item ) ) );

        item.setType( "jar" );

        // pre-create item
        item.setVersion( "3.1" );
        createArtifact( item );
        item.setVersion( null );

        mojo.execute();

        this.assertFileExists( item, true );
        assertEquals( "3.1", item.getVersion() );
    }

    public void testMissingVersionFromDependencyMgtWithClassifier()
        throws Exception
    {
        ArtifactItem item = new ArtifactItem();

        item.setArtifactId( "artifactId" );
        item.setClassifier( "classifier" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        MavenProject project = mojo.getProject();
        project.setDependencies( getDependencyList( item ) );

        item = new ArtifactItem();

        item.setArtifactId( "artifactId-2" );
        item.setClassifier( "classifier" );
        item.setGroupId( "groupId" );
        item.setType( "type" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );

        mojo.setArtifactItems( list );

        project.getDependencyManagement().setDependencies( createDependencyArtifacts( getDependencyMgtList( item ) ) );

        mojo.execute();

        this.assertFileExists( item, true );
        assertEquals( "3.1", item.getVersion() );
    }

    public void testArtifactNotFound()
        throws Exception
    {
        dotestArtifactExceptions( false, true );
    }

    public void testArtifactResolutionException()
        throws Exception
    {
        dotestArtifactExceptions( true, false );
    }

    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" );

        List<ArtifactItem> list = new ArrayList<>();
        list.add( item );
        mojo.setArtifactItems( list );

        try
        {
            mojo.execute();
            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 testCopyDontOverWriteReleases()
        throws Exception
    {
        stubFactory.setCreateFiles( true );
        Artifact release = stubFactory.getReleaseArtifact();
        assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) );

        ArtifactItem item = new ArtifactItem( release );

        List<ArtifactItem> list = new ArrayList<>( 1 );
        list.add( item );
        mojo.setArtifactItems( list );

        mojo.setOverWriteIfNewer( false );

        mojo.execute();

        File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() );

        Thread.sleep( 100 );
        // round up to the next second
        long time = System.currentTimeMillis() + 1000;
        time = time - ( time % 1000 );
        copiedFile.setLastModified( time );
        Thread.sleep( 100 );

        mojo.execute();

        assertEquals( time, copiedFile.lastModified() );
    }

    public void testCopyDontOverWriteSnapshots()
        throws Exception
    {
        stubFactory.setCreateFiles( true );
        Artifact artifact = stubFactory.getSnapshotArtifact();
        assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) );

        ArtifactItem item = new ArtifactItem( artifact );

        List<ArtifactItem> list = new ArrayList<>( 1 );
        list.add( item );
        mojo.setArtifactItems( list );

        mojo.setOverWriteIfNewer( false );

        mojo.execute();

        File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() );

        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 );

        mojo.execute();

        assertEquals( time, copiedFile.lastModified() );
    }

    public void testCopyOverWriteReleases()
        throws Exception
    {
        stubFactory.setCreateFiles( true );
        Artifact release = stubFactory.getReleaseArtifact();
        assertTrue( release.getFile().setLastModified( 1000L ) );
        assertEquals( 1000L, release.getFile().lastModified() );         

        ArtifactItem item = new ArtifactItem( release );

        List<ArtifactItem> list = new ArrayList<>( 1 );
        list.add( item );
        mojo.setArtifactItems( list );

        mojo.setOverWriteIfNewer( false );
        mojo.setOverWriteReleases( true );
        mojo.execute();

        File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() );

        assertTrue( copiedFile.setLastModified( 2000L ) );
        assertEquals( 2000L, copiedFile.lastModified() );

        mojo.execute();

        long timeCopyNow = copiedFile.lastModified();
        assertEquals( 1000L, timeCopyNow );
    }

    public void testCopyOverWriteSnapshot()
        throws Exception
    {
        stubFactory.setCreateFiles( true );
        Artifact artifact = stubFactory.getSnapshotArtifact();
        assertTrue( artifact.getFile().setLastModified( 1000L ) );
        assertEquals( 1000L, artifact.getFile().lastModified() );         

        ArtifactItem item = new ArtifactItem( artifact );

        List<ArtifactItem> list = new ArrayList<>( 1 );
        list.add( item );
        mojo.setArtifactItems( list );

        mojo.setOverWriteIfNewer( false );
        mojo.setOverWriteReleases( false );
        mojo.setOverWriteSnapshots( true );
        mojo.execute();

        File copiedFile = new File( item.getOutputDirectory(), item.getDestFileName() );

        assertTrue( copiedFile.setLastModified( 2000L ) );
        assertEquals( 2000L, copiedFile.lastModified() );

        mojo.execute();

        long timeCopyNow = copiedFile.lastModified();
        assertEquals( 1000L, timeCopyNow );
    }

    public void testCopyOverWriteIfNewer()
        throws Exception
    {
        stubFactory.setCreateFiles( true );
        Artifact artifact = stubFactory.getSnapshotArtifact();
        assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) );

        ArtifactItem item = new ArtifactItem( artifact );

        List<ArtifactItem> list = new ArrayList<>( 1 );
        list.add( item );
        mojo.setArtifactItems( list );
        mojo.setOverWriteIfNewer( true );
        mojo.execute();

        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 ) );

        // set source to be newer
        assertTrue( artifact.getFile().setLastModified( time + 4000 ) );
        mojo.execute();

        assertTrue( time < copiedFile.lastModified() );
    }

    public void testCopyFileWithOverideLocalRepo()
        throws Exception
    {
        final File localRepo = stubFactory.getWorkingDir();

        List<ArtifactItem> list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() );

        mojo.setArtifactItems( list );

        File execLocalRepo = new File( this.testDir.getAbsolutePath(), "executionLocalRepo" );
        assertFalse( execLocalRepo.exists() );

        stubFactory.setWorkingDir( execLocalRepo );
        createArtifactItemArtifacts( list );

        assertFalse( "default local repo should not exist", localRepo.exists() );

        mojo.setLocalRepositoryDirectory( execLocalRepo );

        mojo.execute();

        assertFilesExist( list, true );

    }

    private List<Dependency> createDependencyArtifacts( List<Dependency> 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<ArtifactItem> createArtifactItemArtifacts( List<ArtifactItem> items )
        throws IOException
    {
        for ( ArtifactItem item : items )
        {
            createArtifact( item );
        }
        return items;
    }

    private ArtifactItem createArtifact( ArtifactItem item )
        throws IOException
    {
        stubFactory.setCreateFiles( true );

        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 );
        return item;
    }
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/AbstractDependencyMojoTestCase.java<|end_filename|>
package org.apache.maven.plugins.dependency;

/*
 * 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.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.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
{

    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, 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() );

        stubFactory = new DependencyArtifactStubFactory( this.testDir, createFiles, flattenedPath );
    }

    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() );
            }
            assertFalse( testDir.exists() );
        }
    }

    protected void copyFile( AbstractDependencyMojo mojo, File artifact, File destFile )
        throws MojoExecutionException
    {
        mojo.copyFile( artifact, destFile );
    }
    

    protected void installLocalRepository( LegacySupport legacySupport )
        throws ComponentLookupException
    {
        DefaultRepositorySystemSession repoSession =
            (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 );
    }
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestDestFileFilter.java<|end_filename|>
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
 * 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.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.shared.artifact.filter.collection.ArtifactFilterException;

/**
 * @author brianf
 */
public class TestDestFileFilter
    extends TestCase
{
    Set<Artifact> artifacts = new HashSet<>();

    Log log = new SilentLog();

    File outputFolder;

    DependencyArtifactStubFactory fact;

    protected void setUp()
        throws Exception
    {
        super.setUp();

        outputFolder = new File( "target/markers/" );
        FileUtils.deleteDirectory( outputFolder );
        assertFalse( outputFolder.exists() );

        this.fact = new DependencyArtifactStubFactory( outputFolder, false );
        artifacts = fact.getReleaseAndSnapshotArtifacts();
    }

    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, 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, outputFolder, artifact );
        File destFile =
            new File( destFolder,
                      DependencyUtil.getFormattedFileName( artifact, removeVersion, false, false, removeClassifier ) );

        destFile.getParentFile().mkdirs();
        assertTrue( destFile.createNewFile() );
        return destFile;
    }

    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 ) );

        filter.setOverWriteReleases( true );
        assertTrue( filter.isArtifactIncluded( artifact ) );
    }

    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 ) );

        filter.setOverWriteSnapshots( true );
        assertTrue( filter.isArtifactIncluded( artifact ) );
    }

    public void testDestFileStripVersion()
        throws IOException, ArtifactFilterException
    {
        DestFileFilter filter = new DestFileFilter( outputFolder );
        Artifact artifact = fact.getSnapshotArtifact();
        filter.setRemoveVersion( true );

        assertTrue( filter.isArtifactIncluded( artifact ) );
        createFile( artifact, false, false, true );
        assertFalse( filter.isArtifactIncluded( artifact ) );

        filter.setOverWriteSnapshots( true );
        assertTrue( filter.isArtifactIncluded( artifact ) );
    }

    public void testDestFileStripClassifier()
        throws IOException, ArtifactFilterException
    {
        DestFileFilter filter = new DestFileFilter( outputFolder );
        Artifact artifact = fact.getSnapshotArtifact();
        filter.setRemoveClassifier( true );

        assertTrue( filter.isArtifactIncluded( artifact ) );
        createFile( artifact, false, false, false, true );
        assertFalse( filter.isArtifactIncluded( artifact ) );

        filter.setOverWriteSnapshots( true );
        assertTrue( filter.isArtifactIncluded( artifact ) );
    }

    public void testDestFileSubPerArtifact()
        throws IOException, ArtifactFilterException
    {
        DestFileFilter filter = new DestFileFilter( outputFolder );
        Artifact artifact = fact.getSnapshotArtifact();
        filter.setUseSubDirectoryPerArtifact( true );

        assertTrue( filter.isArtifactIncluded( artifact ) );
        createFile( artifact, true, false, false );
        assertFalse( filter.isArtifactIncluded( artifact ) );

        filter.setOverWriteSnapshots( true );
        assertTrue( filter.isArtifactIncluded( artifact ) );
    }

    public void testDestFileSubPerType()
        throws MojoExecutionException, IOException, ArtifactFilterException
    {
        DestFileFilter filter = new DestFileFilter( outputFolder );
        Artifact artifact = fact.getSnapshotArtifact();
        filter.setUseSubDirectoryPerType( true );

        assertTrue( filter.isArtifactIncluded( artifact ) );
        createFile( artifact, false, true, false );
        assertFalse( filter.isArtifactIncluded( artifact ) );

        filter.setOverWriteSnapshots( true );
        assertTrue( filter.isArtifactIncluded( artifact ) );
    }

    public void testDestFileOverwriteIfNewer()
        throws MojoExecutionException, IOException, ArtifactFilterException
    {
        DestFileFilter filter = new DestFileFilter( outputFolder );

        fact.setCreateFiles( true );
        Artifact artifact = fact.getSnapshotArtifact();
        File artifactFile = artifact.getFile();
        assertTrue( artifactFile.setLastModified( artifactFile.lastModified() ) );
        filter.setOverWriteIfNewer( true );

        // should pass because the file doesn't exist yet.
        assertTrue( filter.isArtifactIncluded( artifact ) );

        // create the file in the destination
        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 ) );

        // now set the last modified timestamp to be newer than the source
        assertTrue( destFile.setLastModified( artifactFile.lastModified() + 1000 ) );

        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() );
    }
}


<|start_filename|>src/test/java/org/apache/maven/plugins/dependency/utils/filters/TestResolveMarkerFileFilter.java<|end_filename|>
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
 * 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.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.shared.artifact.filter.collection.ArtifactFilterException;

/**
 * @author brianf
 */
public class TestResolveMarkerFileFilter
    extends TestCase
{
    Set<Artifact> artifacts = new HashSet<>();

    Log log = new SilentLog();

    File outputFolder;

    DependencyArtifactStubFactory fact;

    protected void setUp()
        throws Exception
    {
        super.setUp();

        outputFolder = new File( "target/markers/" );
        FileUtils.deleteDirectory( outputFolder );
        assertFalse( outputFolder.exists() );

        this.fact = new DependencyArtifactStubFactory( outputFolder, false );
        artifacts = fact.getReleaseAndSnapshotArtifacts();
    }

    protected void tearDown()
        throws IOException
    {
        FileUtils.deleteDirectory( outputFolder );
    }

    public void testResolveFile()
        throws IOException, ArtifactFilterException, MojoExecutionException
    {
        SourcesFileMarkerHandler handler = new SourcesFileMarkerHandler( outputFolder );

        Artifact artifact = fact.getReleaseArtifact();
        handler.setArtifact( artifact );

        ResolveFileFilter filter = new ResolveFileFilter( handler );

        assertTrue( filter.isArtifactIncluded( artifact ) );
        handler.setMarker();
        assertFalse( filter.isArtifactIncluded( artifact ) );
    }

}
