Example usage for org.apache.maven.artifact Artifact getDependencyTrail

List of usage examples for org.apache.maven.artifact Artifact getDependencyTrail

Introduction

In this page you can find the example usage for org.apache.maven.artifact Artifact getDependencyTrail.

Prototype

List<String> getDependencyTrail();

Source Link

Usage

From source file:com.all4tec.sa.maven.proguard.ProGuardMojo.java

License:Apache License

private static File getProguardJar(ProGuardMojo mojo) throws MojoExecutionException {

    Artifact proguardArtifact = null;/*from ww  w . j av a 2s  .  c  o m*/
    int proguardArtifactDistance = -1;
    // This should be solved in Maven 2.1
    for (Iterator i = mojo.pluginArtifacts.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();
        mojo.getLog().debug("pluginArtifact: " + artifact.getFile());
        if (artifact.getArtifactId().startsWith("proguard")
                && !artifact.getArtifactId().startsWith("proguard-maven-plugin")) {
            int distance = artifact.getDependencyTrail().size();
            mojo.getLog().debug("proguard DependencyTrail: " + distance);
            if ((mojo.proguardVersion != null) && (mojo.proguardVersion.equals(artifact.getVersion()))) {
                proguardArtifact = artifact;
                break;
            } else if (proguardArtifactDistance == -1) {
                proguardArtifact = artifact;
                proguardArtifactDistance = distance;
            } else if (distance < proguardArtifactDistance) {
                proguardArtifact = artifact;
                proguardArtifactDistance = distance;
            }
        }
    }
    if (proguardArtifact != null) {
        mojo.getLog().debug("proguardArtifact: " + proguardArtifact.getFile());
        return proguardArtifact.getFile().getAbsoluteFile();
    }
    mojo.getLog().info("proguard jar not found in pluginArtifacts");

    ClassLoader cl;
    cl = mojo.getClass().getClassLoader();
    // cl = Thread.currentThread().getContextClassLoader();
    String classResource = "/" + mojo.proguardMainClass.replace('.', '/') + ".class";
    URL url = cl.getResource(classResource);
    if (url == null) {
        throw new MojoExecutionException(
                "Obfuscation failed ProGuard (" + mojo.proguardMainClass + ") not found in classpath");
    }
    String proguardJar = url.toExternalForm();
    if (proguardJar.startsWith("jar:file:")) {
        proguardJar = proguardJar.substring("jar:file:".length());
        proguardJar = proguardJar.substring(0, proguardJar.indexOf('!'));
    } else {
        throw new MojoExecutionException("Unrecognized location (" + proguardJar + ") in classpath");
    }
    return new File(proguardJar);
}

From source file:com.github.wvengen.maven.proguard.ProGuardMojo.java

License:Apache License

private File getProguardJar(ProGuardMojo mojo) throws MojoExecutionException {

    Artifact proguardArtifact = null;/*from   w  ww .  ja  va 2  s .c om*/
    int proguardArtifactDistance = -1;
    // This should be solved in Maven 2.1
    for (Iterator i = mojo.pluginArtifacts.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();
        mojo.getLog().debug("pluginArtifact: " + artifact.getFile());
        if (artifact.getArtifactId().startsWith(proguardJar)
                && !artifact.getArtifactId().startsWith("proguard-maven-plugin")) {
            int distance = artifact.getDependencyTrail().size();
            mojo.getLog().debug("proguard DependencyTrail: " + distance);
            if ((mojo.proguardVersion != null) && (mojo.proguardVersion.equals(artifact.getVersion()))) {
                proguardArtifact = artifact;
                break;
            } else if (proguardArtifactDistance == -1) {
                proguardArtifact = artifact;
                proguardArtifactDistance = distance;
            } else if (distance < proguardArtifactDistance) {
                proguardArtifact = artifact;
                proguardArtifactDistance = distance;
            }
        }
    }
    if (proguardArtifact != null) {
        mojo.getLog().debug("proguardArtifact: " + proguardArtifact.getFile());
        return proguardArtifact.getFile().getAbsoluteFile();
    }
    mojo.getLog().info("proguard jar not found in pluginArtifacts");

    ClassLoader cl;
    cl = mojo.getClass().getClassLoader();
    // cl = Thread.currentThread().getContextClassLoader();
    String classResource = "/" + mojo.proguardMainClass.replace('.', '/') + ".class";
    URL url = cl.getResource(classResource);
    if (url == null) {
        throw new MojoExecutionException(
                "Obfuscation failed ProGuard (" + mojo.proguardMainClass + ") not found in classpath");
    }
    String proguardJar = url.toExternalForm();
    if (proguardJar.startsWith("jar:file:")) {
        proguardJar = proguardJar.substring("jar:file:".length());
        proguardJar = proguardJar.substring(0, proguardJar.indexOf('!'));
    } else {
        throw new MojoExecutionException("Unrecognized location (" + proguardJar + ") in classpath");
    }
    return new File(proguardJar);
}

From source file:com.redhat.tools.nexus.maven.plugin.descriptor.PluginDescriptorMojo.java

License:Open Source License

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    if (!mavenProject.getPackaging().equals(mapping.getPluginPackaging())) {
        getLog().info("Project is not of packaging type '" + mapping.getPluginPackaging() + "'.");
        return;//from w w  w  . j  a  v a 2  s  .co  m
    }

    initConfig();

    final PluginMetadataGenerationRequest request = new PluginMetadataGenerationRequest();
    request.setGroupId(mavenProject.getGroupId());
    request.setArtifactId(mavenProject.getArtifactId());
    request.setVersion(mavenProject.getVersion());
    request.setName(mavenProject.getName());
    request.setDescription(mavenProject.getDescription());
    request.setPluginSiteURL(mavenProject.getUrl());

    request.setApplicationId(applicationId);
    request.setApplicationEdition(applicationEdition);
    request.setApplicationMinVersion(applicationMinVersion);
    request.setApplicationMaxVersion(applicationMaxVersion);

    // licenses
    if (mavenProject.getLicenses() != null) {
        for (final License mavenLicenseModel : (List<License>) mavenProject.getLicenses()) {
            request.addLicense(mavenLicenseModel.getName(), mavenLicenseModel.getUrl());
        }
    }

    // scm information
    try {
        final ScmRepository repository = getScmRepository();

        final SvnInfoScmResult scmResult = scmInfo(repository, new ScmFileSet(mavenProject.getBasedir()));

        if (!scmResult.isSuccess()) {
            throw new ScmException(scmResult.getCommandOutput());
        }

        final SvnInfoItem info = (SvnInfoItem) scmResult.getInfoItems().get(0);

        request.setScmVersion(info.getLastChangedRevision());
        request.setScmTimestamp(info.getLastChangedDate());
    } catch (final ScmException e) {
        getLog().warn("Failed to get scm information: " + e.getMessage());
    }

    // dependencies
    final List<Artifact> artifacts = mavenProject.getTestArtifacts();
    final Set<Artifact> classpathArtifacts = new HashSet<Artifact>();
    if (artifacts != null) {
        final Set<String> excludedArtifactIds = new HashSet<String>();
        final ArtifactSelector selector = artifactSet == null ? null
                : new ArtifactSelector(mavenProject.getArtifact(), artifactSet);

        artifactLoop: for (final Artifact artifact : artifacts) {
            final GAVCoordinate artifactCoordinate = new GAVCoordinate(artifact.getGroupId(),
                    artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier(),
                    artifact.getType());

            if (artifact.getType().equals(mapping.getPluginPackaging())) {
                if (artifact.isSnapshot()) {
                    artifactCoordinate.setVersion(artifact.getBaseVersion());
                }

                if (!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) {
                    throw new MojoFailureException("Plugin dependency \"" + artifact.getDependencyConflictId()
                            + "\" must have the \"provided\" scope!");
                }

                excludedArtifactIds.add(artifact.getId());

                request.addPluginDependency(artifactCoordinate);
            } else if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                    || Artifact.SCOPE_TEST.equals(artifact.getScope())) {
                excludedArtifactIds.add(artifact.getId());
            } else if ((Artifact.SCOPE_COMPILE.equals(artifact.getScope())
                    || Artifact.SCOPE_RUNTIME.equals(artifact.getScope()))
                    && (!mapping.matchesCoreGroupIds(artifact.getGroupId()))) {
                if (artifact.getDependencyTrail() != null) {
                    for (final String trailId : (List<String>) artifact.getDependencyTrail()) {
                        if (excludedArtifactIds.contains(trailId)) {
                            getLog().debug("Dependency artifact: " + artifact.getId()
                                    + " is part of the transitive dependency set for a dependency with 'provided' or 'test' scope: "
                                    + trailId + "\nThis artifact will be excluded from the plugin classpath.");
                            continue artifactLoop;
                        }
                    }
                }

                if (selector == null || selector.isSelected(artifact)) {
                    if (componentDependencies != null && componentDependencies
                            .contains(artifact.getGroupId() + ":" + artifact.getArtifactId())) {
                        artifactCoordinate.setHasComponents(true);
                    }

                    request.addClasspathDependency(artifactCoordinate);
                    classpathArtifacts.add(artifact);
                } else {
                    getLog().debug("Excluding: " + artifact.getId() + "; excluded by artifactSet.");
                    excludedArtifactIds.add(artifact.getId());
                }
            }
        }
    }

    request.setOutputFile(generatedPluginMetadata);
    request.setClassesDirectory(new File(mavenProject.getBuild().getOutputDirectory()));
    try {
        if (mavenProject.getCompileClasspathElements() != null) {
            for (final String classpathElement : (List<String>) mavenProject.getCompileClasspathElements()) {
                request.getClasspath().add(new File(classpathElement));
            }
        }
    } catch (final DependencyResolutionRequiredException e) {
        throw new MojoFailureException("Plugin failed to resolve dependencies: " + e.getMessage(), e);
    }

    request.getAnnotationClasses().add(ExtensionPoint.class);
    request.getAnnotationClasses().add(Managed.class);

    // do the work
    try {
        metadataGenerator.generatePluginDescriptor(request);
    } catch (final GleanerException e) {
        throw new MojoFailureException("Failed to generate plugin xml file: " + e.getMessage(), e);
    }

    try {
        ClasspathUtils.write(classpathArtifacts, mavenProject);
    } catch (final IOException e) {
        throw new MojoFailureException("Failed to generate classpath properties file: " + e.getMessage(), e);
    }
}

From source file:com.sun.enterprise.module.maven.MavenProjectRepository.java

License:Open Source License

private MavenModuleDefinition buildModule(Artifact a, Map<ModuleId, ModuleDefinition> moduleDefs,
        List<URI> libraries) throws IOException {

    File jarFile = a.getFile();/*from w  w  w . j  av  a 2s. co m*/
    if (jarFile == null || (!jarFile.getName().endsWith(".jar") && !jarFile.isDirectory()))
        // between the compile phase and the package phase, the main artifact is
        // set to the target/classes. allow that to be used as a jar.
        return null;

    MavenModuleDefinition moduleDef = loadJar(jarFile);
    if (moduleDef.getManifest().getMainAttributes().getValue(ManifestConstants.BUNDLE_NAME) == null) {
        // project.getArtifacts() pick up all the transitive dependencies,
        // including to the normal jar files through modules.
        libraries.add(jarFile.toURI());
        return null;
    }

    if (logger.isLoggable(Level.CONFIG))
        logger.config("Adding module " + a.getId() + " trail: " + a.getDependencyTrail());

    moduleDefs.put(AbstractFactory.getInstance().createModuleId(moduleDef), moduleDef);
    return moduleDef;
}

From source file:com.sun.enterprise.module.maven.Packager.java

License:Open Source License

public Map<String, String> configureManifest(MavenProject pom, MavenArchiveConfiguration archive,
        File classesDirectory) throws IOException {
    Map<String, String> entries;
    if (archive != null)
        entries = archive.getManifestEntries();
    else/*from   w ww. j  a  v  a2s. co  m*/
        entries = new HashMap<String, String>();

    entries.put(ManifestConstants.BUNDLE_NAME, pom.getGroupId() + '.' + pom.getArtifactId());

    // check META-INF/services/xxx.ImportPolicy to fill in Import-Policy
    configureImportPolicy(classesDirectory, entries, ImportPolicy.class, ManifestConstants.IMPORT_POLICY);
    configureImportPolicy(classesDirectory, entries, LifecyclePolicy.class, ManifestConstants.LIFECYLE_POLICY);

    // check direct dependencies to find out dependency modules.
    // we don't need to list transitive dependencies here, so use getDependencyArtifacts().

    TokenListBuilder dependencyModuleNames = new TokenListBuilder();
    Set<String> dependencyModules = new HashSet<String>(); // used to find transitive dependencies through other modules.
    for (Artifact a : (Set<Artifact>) pom.getDependencyArtifacts()) {
        if (a.getScope() != null && a.getScope().equals("test"))
            continue;
        // http://www.nabble.com/V3-gf%3Arun-throws-NPE-tf4816802.html indicates
        // that some artifacts are not resolved at this point. Not sure when that could happen
        // so aborting with diagnostics if we find it. We need to better understand what this
        // means and work accordingly. - KK
        if (a.getFile() == null) {
            throw new AssertionError(a.getId() + " is not resolved. a=" + a);
        }
        Jar jar;
        try {
            jar = Jar.create(a.getFile());
        } catch (IOException ioe) {
            // not a jar file, so continue.
            continue;
        }
        Manifest manifest = jar.getManifest();
        String name = null;
        if (manifest != null) {
            Attributes attributes = manifest.getMainAttributes();

            name = attributes.getValue(ManifestConstants.BUNDLE_NAME);
        }
        if (name != null) {
            // this is a hk2 module
            if (!a.isOptional())
                dependencyModuleNames.add(name);

            // even optional modules need to be listed here
            dependencyModules.add(a.getGroupId() + '.' + a.getArtifactId() + ':' + a.getVersion());
        }
    }

    // find jar files to be listed in Class-Path. This needs to include transitive
    // dependencies, except when the path involves a hk2 module.
    TokenListBuilder classPathNames = new TokenListBuilder(" ");
    TokenListBuilder classPathIds = new TokenListBuilder(" ");
    for (Artifact a : (Set<Artifact>) pom.getArtifacts()) {
        // check the trail. does that include hk2 module in the path?
        boolean throughModule = false;
        for (String module : dependencyModules)
            throughModule |= a.getDependencyTrail().get(1).toString().startsWith(module);
        if (throughModule)
            continue; // yep

        if (a.getScope().equals("system") || a.getScope().equals("provided") || a.getScope().equals("test"))
            continue; // ignore tools.jar and such dependencies.

        if (a.isOptional())
            continue; // optional dependency

        classPathNames.add(stripVersion(a));
        classPathIds.add(a.getId());
    }
    if (!classPathNames.isEmpty()) {
        String existingClassPath = entries.get(ManifestConstants.CLASS_PATH);
        if (existingClassPath != null)
            entries.put(ManifestConstants.CLASS_PATH, existingClassPath + " " + classPathNames);
        else
            entries.put(ManifestConstants.CLASS_PATH, classPathNames.toString());

        entries.put(ManifestConstants.CLASS_PATH_ID, classPathIds.toString());
    }

    return entries;
}

From source file:guru.nidi.maven.tools.dependency.DotCreator.java

License:Apache License

private Collection<Artifact> calcDependencies(Artifact artifact) {
    artifact.setScope(null);//from w w w  .  j av  a  2 s.  c  om
    final ArtifactResolutionResult res = mavenContext.resolveArtifact(artifact, parameters);
    for (Iterator<Artifact> it = res.getArtifacts().iterator(); it.hasNext();) {
        final Artifact a = it.next();
        if (a.equals(artifact) || !parameters.include(a) || a.getDependencyTrail().size() != 2) {
            it.remove();
        }
    }
    if (res.getArtifacts().isEmpty() && !res.getMissingArtifacts().isEmpty()) {
        return null;
    }
    return res.getArtifacts();
}

From source file:ninja.maven.NinjaRunMojo.java

License:Apache License

/**
 * This might be a bit hacky. But just a little bit.
 * //  w  w  w .  j  ava2 s  . co m
 * We have to add ninja-standalone and all of its dependencies to
 * the classpath, so that NinjaJetty can start.
 * 
 * But we do not want the user to declare the dependencies inside his
 * project pom.xml.
 * 
 * Therefore we declare the dependency in this plugin pom.xml.
 * But we do not want to include all of this plugin's dependencies in the
 * classpath for NinjaJetty. Therefore this method filters everything and 
 * only adds  dependencies (also transitive deps) that originate
 * from ninja-standalone. That way we get all deps we need.
 * 
 * @param artifacts A list of artifacts that will be filtered.
 * @return All artifacts coming from artifactId "ninja-standalone" 
 *         (including transitive dependencies)
 */
protected List<Artifact> getAllArtifactsComingFromNinjaStandalone(List<Artifact> artifacts) {

    List<Artifact> resultingArtifacts = new ArrayList<>();

    for (Artifact artifact : artifacts) {

        for (String dependencyTrail : artifact.getDependencyTrail()) {

            // something like:  org.ninjaframework:ninja-standalone:jar:2.5.2
            if (dependencyTrail.contains(NinjaMavenPluginConstants.NINJA_STANDALONE_ARTIFACT_ID)) {

                resultingArtifacts.add(artifact);
                break;

            }

        }

    }

    return resultingArtifacts;

}

From source file:ninja.NinjaRunMojo.java

License:Apache License

/**
 * This might be a bit hacky. But just a little bit.
 * /*from  w  ww . j  a v  a  2  s .  c  o m*/
 * We have to add ninja-standalone and all of its dependencies to
 * the classpath, so that NinjaJetty can start.
 * 
 * But we do not want the user to declare the dependencies inside his
 * project pom.xml.
 * 
 * Therefore we declare the dependency in this plugin pom.xml.
 * But we do not want to include all of this plugin's dependencies in the
 * classpath for NinjaJetty. Therefore this method filters everything and 
 * only adds  dependencies (also transitive deps) that originate
 * from ninja-standalone. That way we get all deps we need.
 * 
 * @param artifacts A list of artifacts that will be filtered.
 * @return All artifacts coming from artifactId "ninja-standalone" 
 *         (including transitive dependencies)
 */
private List<org.apache.maven.artifact.Artifact> getAllArtifactsComingFromNinjaStandalone(
        List<org.apache.maven.artifact.Artifact> artifacts) {

    List<org.apache.maven.artifact.Artifact> resultingArtifacts = new ArrayList<>();

    for (org.apache.maven.artifact.Artifact artifact : artifacts) {

        for (String dependencyTrail : artifact.getDependencyTrail()) {

            // something like:  org.ninjaframework:ninja-standalone:jar:2.5.2
            if (dependencyTrail.contains(NinjaMavenPluginConstants.NINJA_STANDALONE_ARTIFACT_ID)) {

                resultingArtifacts.add(artifact);
                break;

            }

        }

    }

    return resultingArtifacts;

}

From source file:org.apache.felix.tools.maven.plugin.OsgiJarMojo.java

License:Apache License

/**
 * We are going to iterate through the POM's specified JAR dependencies. If
 * a dependency has a scope of either RUNTIME or COMPILE, then we'll JAR
 * them up inside the OSGi bundle artifact. We will then add the
 * Bundle-Classpath manifest entry.//from  w  w w  . java  2s .c  om
  *
  * Artifacts which are inlined will not be included.
 */
private void addEmbeddedJars() throws MojoExecutionException {
    Set artifacts = project.getArtifacts();
    Map artifactMap = ArtifactUtils.artifactMapByArtifactId(artifacts);

    for (Iterator it = artifacts.iterator(); it.hasNext();) {
        Artifact artifact = (Artifact) it.next();
        if (!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                && !Artifact.SCOPE_TEST.equals(artifact.getScope())) {
            String type = artifact.getType();

            if ("jar".equals(type)) {
                // Do not include artifacts which are inlined
                if (!(inlinedArtifacts.contains(artifact.getArtifactId()))) {

                    // Do not include artifacts provided by another bundle
                    boolean isProvidedByBundle = false;
                    Iterator iter = artifact.getDependencyTrail().iterator();
                    iter.next(); // skip this project
                    while (iter.hasNext()) {
                        String id = (String) iter.next();
                        Artifact element = (Artifact) artifactMap.get(id);
                        if (element != null && "osgi-bundle".equals(element.getType())) {
                            isProvidedByBundle = true;
                            break;
                        }
                    }
                    if (isProvidedByBundle)
                        continue;

                    File depFile = artifact.getFile();

                    try {
                        FileUtils.copyFileToDirectory(depFile, outputDirectory);

                    } catch (Exception e) {
                        String errmsg = "Error copying " + depFile.getAbsolutePath() + " to "
                                + outputDirectory.getAbsolutePath();
                        throw new MojoExecutionException(errmsg, e);
                    }
                }
            }
        }
    }
}

From source file:org.codehaus.mojo.natives.plugin.NativeLinkMojo.java

License:Open Source License

/**
 * /*w  w w  .ja va  2s  . c o  m*/
 */
private void attachPrimaryArtifact() {
    Artifact artifact = this.project.getArtifact();

    if (null == this.classifier) {
        artifact.setFile(new File(this.linkerOutputDirectory + "/" + this.project.getBuild().getFinalName()
                + "." + this.project.getArtifact().getArtifactHandler().getExtension()));
    } else {
        //install primary artifact as a classifier

        DefaultArtifact clone = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(),
                artifact.getVersionRange().cloneOf(), artifact.getScope(), artifact.getType(), classifier,
                artifact.getArtifactHandler(), artifact.isOptional());

        clone.setRelease(artifact.isRelease());
        clone.setResolvedVersion(artifact.getVersion());
        clone.setResolved(artifact.isResolved());
        clone.setFile(artifact.getFile());

        if (artifact.getAvailableVersions() != null) {
            clone.setAvailableVersions(new ArrayList(artifact.getAvailableVersions()));
        }

        clone.setBaseVersion(artifact.getBaseVersion());
        clone.setDependencyFilter(artifact.getDependencyFilter());

        if (artifact.getDependencyTrail() != null) {
            clone.setDependencyTrail(new ArrayList(artifact.getDependencyTrail()));
        }

        clone.setDownloadUrl(artifact.getDownloadUrl());
        clone.setRepository(artifact.getRepository());

        clone.setFile(new File(this.linkerOutputDirectory + "/" + this.project.getBuild().getFinalName() + "."
                + this.project.getArtifact().getArtifactHandler().getExtension()));

        project.setArtifact(clone);
    }
}