Example usage for org.apache.maven.artifact.resolver.filter ArtifactFilter ArtifactFilter

List of usage examples for org.apache.maven.artifact.resolver.filter ArtifactFilter ArtifactFilter

Introduction

In this page you can find the example usage for org.apache.maven.artifact.resolver.filter ArtifactFilter ArtifactFilter.

Prototype

ArtifactFilter

Source Link

Usage

From source file:fr.paris.lutece.maven.AbstractLuteceWebappMojo.java

License:Open Source License

/**
 * Copy third-party JARs to an exploded webapp directory.
 *
 * @param webappDir//from   ww w. j  a  va2  s  .co  m
 *            the webapp directory
 *
 * @throws MojoExecutionException
 *             if an error occurs while copying the files.
 */
protected void copyThirdPartyJars(File webappDir) throws MojoExecutionException {
    File webinfLib = new File(webappDir, "WEB-INF/lib");
    webinfLib.mkdirs();

    // Filter jar artifacts in scope 'compile' or 'runtime'
    ArtifactFilter thirdPartyFilter = new ArtifactFilter() {
        @Override
        public boolean include(Artifact artifact) {
            return ("jar".equals(artifact.getType()) && (Artifact.SCOPE_RUNTIME.equals(artifact.getScope())
                    || Artifact.SCOPE_COMPILE.equals(artifact.getScope())));
        }
    };

    // if multi project
    if ((reactorProjects.size() > 1) && !project.isExecutionRoot()) {
        //add dependencies of modules for filter duplicate entry
        multiProjectArtifacts.addAll(filterArtifacts(thirdPartyFilter));
    } else { // no in multi project

        Set thirdPartyJARs = filterArtifacts(thirdPartyFilter);

        for (Iterator iterJARs = thirdPartyJARs.iterator(); iterJARs.hasNext();) {
            Artifact artifact = (Artifact) iterJARs.next();
            File jarFile = artifact.getFile();
            File newFile = new File(webinfLib, jarFile.getName());

            try {
                FileUtils.copyFileIfModified(jarFile, newFile);
            } catch (IOException e) {
                throw new MojoExecutionException(
                        "Error while copying " + jarFile.getAbsolutePath() + " to " + newFile.getAbsolutePath(),
                        e);
            }
        }
    }
}

From source file:fr.paris.lutece.maven.ExplodedMojo.java

License:Open Source License

/**
 * Use to filter duplicate dependencies in multi project
 *
 * @return a list of artifacts whith no duplicate entry
 *//*from   w ww. j  a  v a  2s . c  om*/
private Set<Artifact> doDependencyResolution() {
    Set<Artifact> artifactsReturn = new HashSet<Artifact>();

    // Collector Filter jar artifacts in scope 'compile' or 'runtime'
    ArtifactFilter thirdPartyFilter = new ArtifactFilter() {
        @Override
        public boolean include(Artifact artifact) {
            return (!LUTECE_CORE_TYPE.equals(artifact.getArtifactId())
                    && !SERVLET_API.equals(artifact.getArtifactId())
                    && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                    && !Artifact.SCOPE_TEST.equals(artifact.getScope()));
        }
    };

    // Collector listener config
    List<ResolutionListener> listeners = new ArrayList<ResolutionListener>();

    if (logger.isDebugEnabled()) {
        listeners.add(new DebugResolutionListener(logger));
    }

    listeners.add(new WarningResolutionListener(logger));

    /*---------------- Resolution-------------*/
    // resolve conflict version artifacts with collector
    ArtifactResolutionResult artifactResolutionResult = null;

    try {
        artifactResolutionResult = artifactCollector.collect(multiProjectArtifacts, project.getArtifact(),
                localRepository, remoteRepositories, metadataSource, thirdPartyFilter, listeners);
    } catch (ArtifactResolutionException e) {
        e.printStackTrace();
    }

    // keep track of added reactor projects in order to avoid duplicates
    Set<String> emittedReactorProjectId = new HashSet<String>();

    for (ResolutionNode node : artifactResolutionResult.getArtifactResolutionNodes()) {
        Artifact art = node.getArtifact();

        try {
            resolver.resolve(art, node.getRemoteRepositories(), localRepository);
        } catch (ArtifactNotFoundException e) {
            e.printStackTrace();
        } catch (ArtifactResolutionException e) {
            e.printStackTrace();
        }

        if (emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId())) {
            artifactsReturn.add(art);
        }
    }

    return artifactsReturn;
}

From source file:me.springframework.di.maven.AbstractGeneratorMojo.java

License:Open Source License

/**
 * Produces the {@link JavaDocBuilder} used to analyze classes and source files.
 * /*from  w  w  w  .  ja v  a  2s .co m*/
 * @return The {@link JavaDocBuilder} used to analyze classes and source files.
 * @throws MojoExecutionException If we fail to produce the {@link JavaDocBuilder}. (Fail
 *             early.)
 */
@SuppressWarnings("unchecked")
private JavaDocBuilder createJavaDocBuilder() throws MojoExecutionException {
    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSourceTree(new File(project.getBuild().getSourceDirectory()));
    // Quick and dirty hack for adding Classloaders with the definitions of
    // classes the sources depend upon.
    try {
        Set<Artifact> artifacts = MavenMetadataSource.createArtifacts(artifactFactory,
                project.getDependencies(), Artifact.SCOPE_RUNTIME, new ArtifactFilter() {

                    public boolean include(Artifact artifact) {
                        return true;
                    }

                }, project);
        List<URL> urls = new ArrayList<URL>();
        for (Artifact artifact : artifacts) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Adding artifact " + artifact.getId());
            }
            if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
                urls.add(artifact.getFile().toURL());
            } else {
                urls.add(new File(localRepository.getBasedir(), localRepository.pathOf(artifact)).toURL());
            }
        }
        URL[] template = new URL[0];
        URLClassLoader loader = new URLClassLoader(urls.toArray(template));
        builder.getClassLibrary().addClassLoader(loader);
    } catch (InvalidDependencyVersionException idve) {
        idve.printStackTrace();
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Malformed artifact URLs.");
    }
    return builder;
}

From source file:npanday.plugin.resolver.CopyDependenciesMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    String skipReason = "";
    if (!skip) {/*from  w  ww  .  ja va 2 s.c o  m*/
        ArtifactType knownType = ArtifactType.getArtifactTypeForPackagingName(project.getPackaging());

        if (knownType.equals(ArtifactType.NULL)) {
            skip = true;
            skipReason = ", because the current project (type:" + project.getPackaging()
                    + ") is not built with NPanday";
        }
    }

    if (skip) {
        getLog().info("NPANDAY-158-001: Mojo for copying dependencies was intentionally skipped" + skipReason);
        return;
    }

    SettingsUtil.applyCustomSettings(getLog(), repositoryRegistry, settingsPath);

    AndArtifactFilter includeFilter = new AndArtifactFilter();

    OrArtifactFilter typeIncludes = new OrArtifactFilter();
    typeIncludes.add(new DotnetExecutableArtifactFilter());
    typeIncludes.add(new DotnetLibraryArtifactFilter());

    if (includePdbs) {
        typeIncludes.add(new DotnetSymbolsArtifactFilter());
    }

    includeFilter.add(typeIncludes);

    if (!Strings.isNullOrEmpty(includeScope)) {
        includeFilter.add(new ScopeArtifactFilter(includeScope));
    }

    Set<Artifact> artifacts;
    try {
        artifacts = dependencyResolution.require(project, LocalRepositoryUtil.create(localRepository),
                includeFilter);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException(
                "NPANDAY-158-003: dependency resolution for scope " + includeScope + " failed!", e);
    }

    /**
     * Should be resolved, but then not copied
     */
    if (!Strings.isNullOrEmpty(excludeScope)) {
        includeFilter.add(new InversionArtifactFilter(new ScopeArtifactFilter(excludeScope)));
    }

    if (skipReactorArtifacts) {
        getLog().info("NPANDAY-158-008: " + reactorProjects);

        includeFilter.add(new InversionArtifactFilter(new ArtifactFilter() {
            public boolean include(Artifact artifact) {
                for (MavenProject project : reactorProjects) {
                    // we don't care about the type and the classifier here
                    if (project.getGroupId().equals(artifact.getGroupId())
                            && project.getArtifactId().equals(artifact.getArtifactId())
                            && project.getVersion().equals(artifact.getVersion())) {
                        return true;
                    }
                }
                return false;
            }
        }));
    }

    for (Artifact dependency : artifacts) {
        if (!includeFilter.include(dependency)) {
            getLog().debug("NPANDAY-158-006: dependency " + dependency + " was excluded");

            continue;
        }

        try {
            File targetFile = new File(outputDirectory, PathUtil.getPlainArtifactFileName(dependency));
            if (!targetFile.exists() || targetFile.lastModified() != dependency.getFile().lastModified()
                    || targetFile.length() != dependency.getFile().length()) {
                getLog().info("NPANDAY-158-004: copy " + dependency.getFile() + " to " + targetFile);
                FileUtils.copyFile(dependency.getFile(), targetFile);
            } else {
                getLog().debug("NPANDAY-158-007: dependency " + dependency + " is yet up to date");
            }
        } catch (IOException ioe) {
            throw new MojoExecutionException("NPANDAY-158-005: Error copying dependency " + dependency, ioe);
        }
    }
}

From source file:npanday.plugin.resolver.ListDependenciesMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    String skipReason = "";
    if (skip) {/* ww w  .  jav a 2  s . c om*/
        getLog().info("NPANDAY-161-001: Mojo for listing dependencies was intentionally skipped" + skipReason);
        return;
    }

    SettingsUtil.applyCustomSettings(getLog(), repositoryRegistry, settingsPath);

    AndArtifactFilter includeFilter = new AndArtifactFilter();

    if (!Strings.isNullOrEmpty(includeScope)) {
        includeFilter.add(new ScopeArtifactFilter(includeScope));
    }

    Set<Artifact> artifacts;
    try {
        // TODO: Workarround. Somehow in the first run, PDBs wont be part of the result!
        dependencyResolution.require(project, LocalRepositoryUtil.create(localRepository), includeFilter);
        artifacts = dependencyResolution.require(project, LocalRepositoryUtil.create(localRepository),
                includeFilter);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException(
                "NPANDAY-161-003: dependency resolution for scope " + includeScope + " failed!", e);
    }

    /**
     * Should be resolved, but then not shown
     */
    if (!Strings.isNullOrEmpty(excludeScope)) {
        includeFilter.add(new InversionArtifactFilter(new ScopeArtifactFilter(excludeScope)));
    }

    if (skipReactorArtifacts) {
        getLog().info("NPANDAY-161-008: " + reactorProjects);

        includeFilter.add(new InversionArtifactFilter(new ArtifactFilter() {
            public boolean include(Artifact artifact) {
                for (MavenProject project : reactorProjects) {
                    // we don't care about the type and the classifier here
                    if (project.getGroupId().equals(artifact.getGroupId())
                            && project.getArtifactId().equals(artifact.getArtifactId())
                            && project.getVersion().equals(artifact.getVersion())) {
                        return true;
                    }
                }
                return false;
            }
        }));
    }

    getLog().info("The following files have been resolved:");
    for (Artifact dependency : artifacts) {
        if (!includeFilter.include(dependency)) {
            getLog().debug("NPANDAY-161-006: dependency " + dependency + " was excluded");
            continue;
        }

        getLog().info("   " + dependency.getId() + ":" + dependency.getScope() + " -> " + dependency.getFile());
    }
}

From source file:org.apache.felix.karaf.tooling.features.GenerateFeaturesXmlMojo.java

License:Apache License

private void readKernelBundles() throws ArtifactResolutionException, ArtifactNotFoundException,
        MojoExecutionException, ZipException, IOException, DependencyTreeBuilderException {
    final Collection<Artifact> kernelArtifacts;
    if (kernelVersion == null) {
        getLog().info("Step 1: Building list of provided bundle exports");
        kernelArtifacts = new HashSet<Artifact>();
        DependencyNode tree = dependencyTreeBuilder.buildDependencyTree(project, localRepo, factory,
                artifactMetadataSource, new ArtifactFilter() {

                    public boolean include(Artifact artifact) {
                        return true;
                    }//from w w  w. ja v  a2 s.c om

                }, new DefaultArtifactCollector());
        tree.accept(new DependencyNodeVisitor() {
            public boolean endVisit(DependencyNode node) {
                // we want the next sibling too
                return true;
            }

            public boolean visit(DependencyNode node) {
                if (node.getState() != DependencyNode.OMITTED_FOR_CONFLICT) {
                    Artifact artifact = node.getArtifact();
                    if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                            && !artifact.getType().equals("pom")) {
                        kernelArtifacts.add(artifact);
                    }
                }
                // we want the children too
                return true;
            }
        });
    } else {
        getLog().info("Step 1 : Building list of kernel exports");
        getLog().warn("Use of 'kernelVersion' is deprecated -- use a dependency with scope 'provided' instead");
        Artifact kernel = factory.createArtifact("org.apache.felix.karaf", "apache-felix-karaf", kernelVersion,
                Artifact.SCOPE_PROVIDED, "pom");
        resolver.resolve(kernel, remoteRepos, localRepo);
        kernelArtifacts = getDependencies(kernel);
    }
    for (Artifact artifact : kernelArtifacts) {
        registerKernelBundle(artifact);
    }
    getLog().info("...done!");
}

From source file:org.apache.felix.karaf.tooling.features.ValidateFeaturesMojo.java

License:Apache License

private void readProvidedBundles() throws Exception {
    DependencyNode tree = dependencyTreeBuilder.buildDependencyTree(project, localRepo, factory,
            artifactMetadataSource, new ArtifactFilter() {

                public boolean include(Artifact artifact) {
                    return true;
                }/*from   w w w  .j av a  2s . com*/

            }, new DefaultArtifactCollector());
    tree.accept(new DependencyNodeVisitor() {
        public boolean endVisit(DependencyNode node) {
            // we want the next sibling too
            return true;
        }

        public boolean visit(DependencyNode node) {
            if (node.getState() != DependencyNode.OMITTED_FOR_CONFLICT) {
                Artifact artifact = node.getArtifact();
                info("    scanning %s for exports", artifact);
                if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !artifact.getType().equals("pom")) {
                    try {
                        for (ManifestEntry entry : ManifestUtils.getExports(getManifest(artifact))) {
                            getLog().debug(" adding " + entry.getName() + " to list of available packages");
                            systemExports.add(entry.getName());
                        }
                    } catch (ArtifactResolutionException e) {
                        error("Unable to find bundle exports for %s: %s", e, artifact, e.getMessage());
                    } catch (ArtifactNotFoundException e) {
                        error("Unable to find bundle exports for %s: %s", e, artifact, e.getMessage());
                    } catch (IOException e) {
                        error("Unable to find bundle exports for %s: %s", e, artifact, e.getMessage());
                    }
                }
            }
            // we want the children too
            return true;
        }
    });
}

From source file:org.apache.karaf.tooling.features.ValidateDescriptorMojo.java

License:Apache License

private void readProvidedBundles() throws Exception {
    DependencyNode tree = dependencyTreeBuilder.buildDependencyTree(project, localRepo, factory,
            artifactMetadataSource, new ArtifactFilter() {

                public boolean include(Artifact artifact) {
                    return true;
                }//from   w  w  w  .j  a  v  a  2  s .c o  m

            }, collector);
    tree.accept(new DependencyNodeVisitor() {
        public boolean endVisit(DependencyNode node) {
            // we want the next sibling too
            return true;
        }

        public boolean visit(DependencyNode node) {
            if (node.getState() != DependencyNode.OMITTED_FOR_CONFLICT) {
                Artifact artifact = node.getArtifact();
                info("    scanning %s for exports", artifact);
                if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !artifact.getType().equals("pom")) {
                    try {
                        for (Clause clause : ManifestUtils.getExports(getManifest("", artifact))) {
                            getLog().debug(" adding " + clause.getName() + " to list of available packages");
                            systemExports.add(clause.getName());
                        }
                    } catch (ArtifactResolutionException e) {
                        error("Unable to find bundle exports for %s: %s", e, artifact, e.getMessage());
                    } catch (ArtifactNotFoundException e) {
                        error("Unable to find bundle exports for %s: %s", e, artifact, e.getMessage());
                    } catch (IOException e) {
                        error("Unable to find bundle exports for %s: %s", e, artifact, e.getMessage());
                    }
                }
            }
            // we want the children too
            return true;
        }
    });
}

From source file:org.apache.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

private void addDependencies(Archiver archiver) throws ArchiverException, MojoExecutionException {

    Log log = getLog();/*from  w  w w.j  a v a  2s.  c  o m*/
    AndArtifactFilter filter = new AndArtifactFilter();
    filter.add(new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME));
    filter.add(new ArtifactFilter() {
        public boolean include(Artifact artifact) {
            return !artifact.isOptional();
        }
    });
    filter.add(new TypeArtifactFilter("jar"));
    filter.add(buildSynapseRuntimeArtifactFilter());
    for (Artifact artifact : filterArtifacts(project.getArtifacts(), filter)) {
        String targetFileName = artifact.getArtifactId() + "-" + artifact.getVersion() + "."
                + artifact.getArtifactHandler().getExtension();
        log.info("Adding " + targetFileName + " (scope " + artifact.getScope() + ")");
        archiver.addFile(artifact.getFile(), "lib/" + targetFileName);
    }
}

From source file:org.apache.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

/**
 * Build a filter that excludes all artifacts that are provided by Synapse at runtime.
 * // w ww . j a  v  a  2  s.com
 * @return
 * @throws MojoExecutionException
 */
private ArtifactFilter buildSynapseRuntimeArtifactFilter() throws MojoExecutionException {
    final Map<String, Artifact> artifacts = new HashMap<String, Artifact>();
    for (Artifact artifact : getSynapseRuntimeArtifacts()) {
        artifacts.put(artifact.getDependencyConflictId(), artifact);
    }
    final Set<String> defaultExclusionSet = new HashSet<String>(Arrays.asList(defaultRuntimeExcludes));
    return new ArtifactFilter() {
        public boolean include(Artifact artifact) {
            Artifact runtimeArtifact = artifacts.get(artifact.getDependencyConflictId());
            if (runtimeArtifact == null) {
                return !defaultExclusionSet.contains(artifact.getDependencyConflictId());
            } else {
                if (!runtimeArtifact.getVersion().equals(artifact.getVersion())) {
                    getLog().warn("Possible runtime version conflict for " + artifact.getArtifactId()
                            + ": XAR depends on " + artifact.getVersion() + ", Synapse runtime provides "
                            + runtimeArtifact.getVersion());
                }
                return false;
            }
        }
    };
}