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

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

Introduction

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

Prototype

boolean isResolved();

Source Link

Usage

From source file:br.com.uggeri.maven.builder.mojo.DependencyResolver.java

public List<Artifact> resolveDependencies(MavenProject project, Artifact artifact)
        throws MojoExecutionException {
    final List<Artifact> artifactDependencies = new ArrayList<Artifact>();
    Artifact pomArtifact = createArtifact(artifact.getGroupId(), artifact.getArtifactId(),
            artifact.getVersion(), "pom");
    resolveArtifact(project, pomArtifact);
    if (pomArtifact.isResolved()) {
        DefaultModelReader dmr = new DefaultModelReader();
        try {//www  .j  a  v  a  2s.  c  o m
            Model pomModel = dmr.read(pomArtifact.getFile(), null);
            for (Dependency dep : pomModel.getDependencies()) {
                final Artifact depArtifact = createArtifact(dep);
                if (log != null && log.isDebugEnabled()) {
                    log.debug("Dependencia encontrada para " + artifact.getId() + ".");
                }
                resolveArtifact(project, depArtifact);
                if (depArtifact.isResolved()) {
                    artifactDependencies.add(depArtifact);
                }
            }
        } catch (IOException ex) {
            throw new MojoExecutionException("Erro ao ler o arquivo POM do artefato " + artifact.getId(), ex);
        }
    }
    return artifactDependencies;
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Resolve the required artifacts for each of the dependency. <code>sources</code> or <code>javadoc</code> artifacts
 * (depending on the <code>classifier</code>) are attached to the dependency.
 *
 * @param deps                      resolved dependencies
 * @param inClassifier              the classifier we are looking for (either <code>sources</code> or <code>javadoc</code>)
 * @param includeRemoteRepositories flag whether we should search remote repositories for the artifacts or not
 * @return the list of dependencies for which the required artifact was not found
 *//*from w  w w . j ava  2  s  .c o  m*/
private List resolveDependenciesWithClassifier(IdeDependency[] deps, String inClassifier,
        boolean includeRemoteRepositories) {
    List missingClassifierDependencies = new ArrayList();

    // if downloadSources is off, just check
    // local repository for reporting missing source jars
    List remoteRepos = includeRemoteRepositories ? getRemoteArtifactRepositories() : Collections.EMPTY_LIST;

    for (int j = 0; j < deps.length; j++) {
        IdeDependency dependency = deps[j];

        if (dependency.isReferencedProject() || dependency.isSystemScoped()) {
            // artifact not needed
            continue;
        }

        if (getLog().isDebugEnabled()) {
            getLog().debug("Searching for sources for " + dependency.getId() + ":" + dependency.getClassifier()
                    + " at " + dependency.getId() + ":" + inClassifier);
        }

        Artifact baseArtifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(),
                dependency.getArtifactId(), dependency.getVersion(), dependency.getType(),
                dependency.getClassifier());
        baseArtifact = IdeUtils.resolveArtifact(artifactResolver, baseArtifact, remoteRepos, localRepository,
                getLog());
        if (!baseArtifact.isResolved()) {
            // base artifact does not exist - no point checking for javadoc/sources
            continue;
        }

        Artifact artifact = IdeUtils.createArtifactWithClassifier(dependency.getGroupId(),
                dependency.getArtifactId(), dependency.getVersion(), dependency.getClassifier(), inClassifier,
                artifactFactory);
        File notAvailableMarkerFile = IdeUtils.getNotAvailableMarkerFile(localRepository, artifact);

        if (forceRecheck && notAvailableMarkerFile.exists()) {
            if (!notAvailableMarkerFile.delete()) {
                getLog().warn(Messages.getString("AbstractIdeSupportMojo.unabletodeletenotavailablemarkerfile",
                        notAvailableMarkerFile));
            }
        }

        if (!notAvailableMarkerFile.exists()) {
            artifact = IdeUtils.resolveArtifact(artifactResolver, artifact, remoteRepos, localRepository,
                    getLog());
            if (artifact.isResolved()) {
                if ("sources".equals(inClassifier)) {
                    dependency.setSourceAttachment(artifact.getFile());
                } else if ("javadoc".equals(inClassifier)) {
                    dependency.setJavadocAttachment(artifact.getFile());
                }
            } else {
                if (includeRemoteRepositories) {
                    try {
                        notAvailableMarkerFile.createNewFile();
                        getLog().debug(
                                Messages.getString("AbstractIdeSupportMojo.creatednotavailablemarkerfile",
                                        notAvailableMarkerFile));
                    } catch (IOException e) {
                        getLog().warn(Messages.getString(
                                "AbstractIdeSupportMojo.failedtocreatenotavailablemarkerfile",
                                notAvailableMarkerFile));
                    }
                }
                // add the dependencies to the list
                // of those lacking the required
                // artifact
                missingClassifierDependencies.add(dependency);
            }
        }
    }

    // return the list of dependencies missing the
    // required artifact
    return missingClassifierDependencies;
}

From source file:com.blackducksoftware.integration.hub.jenkins.maven.HubMavenReporter.java

License:Open Source License

private void recordMavenDependencies(final Set<Artifact> artifacts) {
    if (artifacts != null) {
        for (final Artifact artifact : artifacts) {
            if (artifact.isResolved() && artifact.getFile() != null) {
                final BuildDependency mavenDependency = getDependencyFromArtifact(artifact);
                dependencies.add(mavenDependency);
            }//from  ww  w  .j a v  a  2  s. c  o m
        }
    }
}

From source file:com.edugility.maven.Artifacts.java

License:Open Source License

/**
 * Returns an unmodifiable, non-{@code null} {@link Collection} of
 * {@link Artifact}s, each element of which is a non-{@code null}
 * {@link Artifact} that represents either the supplied {@link
 * MavenProject} itself or a {@linkplain MavenProject#getArtifacts()
 * dependency of it}./* ww w .ja  v  a  2  s.  co  m*/
 *
 * <p>The returned {@link Artifact} {@link Collection} will be
 * sorted in topological order, from an {@link Artifact} with no
 * dependencies as the first element, to the {@link Artifact}
 * representing the {@link MavenProject} itself as the last.</p>
 *
 * <p>All {@link Artifact}s that are not {@linkplain
 * Object#equals(Object) equal to} the return value of {@link
 * MavenProject#getArtifact() project.getArtifact()} will be
 * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest)
 * resolved} if they are not already {@linkplain
 * Artifact#isResolved() resolved}.  No guarantee of {@linkplain
 * Artifact#isResolved() resolution status} is made of the
 * {@linkplain MavenProject#getArtifact() project
 * <code>Artifact</code>}, which in normal&mdash;possibly
 * all?&mdash;cases will be unresolved.</p>
 *
 * @param project the {@link MavenProject} for which resolved {@link
 * Artifact}s should be returned; must not be {@code null}
 *
 * @param dependencyGraphBuilder the {@link DependencyGraphBuilder}
 * instance that will calculate the dependency graph whose postorder
 * traversal will yield the {@link Artifact}s to be resolved; must
 * not be {@code null}
 *
 * @param filter an {@link ArtifactFilter} used during {@linkplain
 * DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter) dependency graph assembly}; may be {@code null}
 *
 * @param resolver an {@link ArtifactResolver} that will use the <a
 * href="http://maven.apache.org/ref/3.0.5/maven-compat/apidocs/src-html/org/apache/maven/artifact/resolver/DefaultArtifactResolver.html#line.335">Maven
 * 3.0.5 <code>Artifact</code> resolution algorithm</a> to resolve
 * {@link Artifact}s returned by the {@link
 * DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter)} method; must not be {@code null}
 *
 * @param localRepository an {@link ArtifactRepository} representing
 * the local Maven repository in effect; may be {@code null}
 *
 * @return a non-{@code null}, {@linkplain
 * Collections#unmodifiableCollection(Collection) unmodifiable}
 * {@link Collection} of non-{@code null} {@link Artifact} instances
 *
 * @exception IllegalArgumentException if {@code project}, {@code
 * dependencyGraphBuilder} or {@code resolver} is {@code null}
 *
 * @exception ArtifactResolutionException if there were problems
 * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest)
 * resolving} {@link Artifact} instances
 *
 * @exception DependencyGraphBuilderException if there were problems
 * {@linkplain
 * DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter) building the dependency graph}
 *
 * @see ArtifactResolver#resolve(ArtifactResolutionRequest)
 *
 * @see DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter)
 */
public Collection<? extends Artifact> getArtifactsInTopologicalOrder(final MavenProject project,
        final DependencyGraphBuilder dependencyGraphBuilder, final ArtifactFilter filter,
        final ArtifactResolver resolver, final ArtifactRepository localRepository)
        throws DependencyGraphBuilderException, ArtifactResolutionException {
    final Logger logger = this.getLogger();
    if (logger != null && logger.isLoggable(Level.FINER)) {
        logger.entering(this.getClass().getName(), "getArtifactsInTopologicalOrder",
                new Object[] { project, dependencyGraphBuilder, filter, resolver, localRepository });
    }
    if (project == null) {
        throw new IllegalArgumentException("project", new NullPointerException("project"));
    }
    if (dependencyGraphBuilder == null) {
        throw new IllegalArgumentException("dependencyGraphBuilder",
                new NullPointerException("dependencyGraphBuilder"));
    }
    if (resolver == null) {
        throw new IllegalArgumentException("resolver", new NullPointerException("resolver"));
    }

    List<Artifact> returnValue = null;

    final DependencyNode projectNode = dependencyGraphBuilder.buildDependencyGraph(project, filter);
    assert projectNode != null;
    final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
    projectNode.accept(visitor);
    final Collection<? extends DependencyNode> nodes = visitor.getNodes();

    if (nodes == null || nodes.isEmpty()) {
        if (logger != null && logger.isLoggable(Level.FINE)) {
            logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder",
                    "No dependency nodes encountered");
        }

    } else {
        final Artifact projectArtifact = project.getArtifact();

        returnValue = new ArrayList<Artifact>();

        for (final DependencyNode node : nodes) {
            if (node != null) {
                Artifact artifact = node.getArtifact();
                if (artifact != null) {

                    if (!artifact.isResolved()) {
                        if (logger != null && logger.isLoggable(Level.FINE)) {
                            logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder",
                                    "Artifact {0} is unresolved", artifact);
                        }

                        if (artifact.equals(projectArtifact)) {
                            // First see if the artifact is the project artifact.
                            // If so, then it by definition won't be able to be
                            // resolved, because it's being built.
                            if (logger != null && logger.isLoggable(Level.FINE)) {
                                logger.logp(Level.FINE, this.getClass().getName(),
                                        "getArtifactsInTopologicalOrder",
                                        "Artifact {0} resolved to project artifact: {1}",
                                        new Object[] { artifact, projectArtifact });
                            }
                            artifact = projectArtifact;

                        } else {
                            // See if the project's associated artifact map
                            // contains a resolved version of this artifact.  The
                            // artifact map contains all transitive dependency
                            // artifacts of the project.  Each artifact in the map
                            // is guaranteed to be resolved.
                            @SuppressWarnings("unchecked")
                            final Map<String, Artifact> artifactMap = project.getArtifactMap();
                            if (artifactMap != null && !artifactMap.isEmpty()) {
                                final Artifact mapArtifact = artifactMap
                                        .get(new StringBuilder(artifact.getGroupId()).append(":")
                                                .append(artifact.getArtifactId()).toString());
                                if (mapArtifact != null) {
                                    if (logger != null && logger.isLoggable(Level.FINE)) {
                                        logger.logp(Level.FINE, this.getClass().getName(),
                                                "getArtifactsInTopologicalOrder",
                                                "Artifact {0} resolved from project artifact map: {1}",
                                                new Object[] { artifact, mapArtifact });
                                    }
                                    artifact = mapArtifact;
                                }
                            }

                            if (!artifact.isResolved()) {
                                // Finally, perform manual artifact resolution.
                                final ArtifactResolutionRequest request = new ArtifactResolutionRequest();
                                request.setArtifact(artifact);
                                request.setLocalRepository(localRepository);
                                @SuppressWarnings("unchecked")
                                final List<ArtifactRepository> remoteRepositories = project
                                        .getRemoteArtifactRepositories();
                                request.setRemoteRepositories(remoteRepositories);

                                if (logger != null && logger.isLoggable(Level.FINE)) {
                                    logger.logp(Level.FINE, this.getClass().getName(),
                                            "getArtifactsInTopologicalOrder",
                                            "Resolving artifact {0} using ArtifactResolutionRequest {1}",
                                            new Object[] { artifact, request });
                                }

                                final ArtifactResolutionResult result = resolver.resolve(request);
                                if (result == null || !result.isSuccess()) {
                                    this.handleArtifactResolutionError(request, result);
                                } else {
                                    @SuppressWarnings("unchecked")
                                    final Collection<? extends Artifact> resolvedArtifacts = (Set<? extends Artifact>) result
                                            .getArtifacts();
                                    if (resolvedArtifacts == null || resolvedArtifacts.isEmpty()) {
                                        if (logger != null && logger.isLoggable(Level.WARNING)) {
                                            logger.logp(Level.WARNING, this.getClass().getName(),
                                                    "getArtifactsInTopologicalOrder",
                                                    "Artifact resolution failed silently for artifact {0}",
                                                    artifact);
                                        }
                                    } else {
                                        final Artifact resolvedArtifact = resolvedArtifacts.iterator().next();
                                        if (resolvedArtifact != null) {
                                            assert resolvedArtifact.isResolved();
                                            artifact = resolvedArtifact;
                                        } else if (logger != null && logger.isLoggable(Level.WARNING)) {
                                            logger.logp(Level.WARNING, this.getClass().getName(),
                                                    "getArtifactsInTopologicalOrder",
                                                    "Artifact resolution failed silently for artifact {0}",
                                                    artifact);
                                        }
                                    }
                                }
                            }

                        }
                    }

                    if (artifact != null) {
                        returnValue.add(artifact);
                    }
                }
            }
        }
        if (!returnValue.isEmpty()) {
            Collections.reverse(returnValue);
            Collections.sort(returnValue, scopeComparator);
        }
    }
    if (returnValue == null) {
        returnValue = Collections.emptyList();
    } else {
        returnValue = Collections.unmodifiableList(returnValue);
    }
    if (logger != null && logger.isLoggable(Level.FINER)) {
        logger.exiting(this.getClass().getName(), "getArtifactsInTopologicalOrder", returnValue);
    }
    return returnValue;
}

From source file:com.edugility.maven.liquibase.LiquibaseChangeLogArtifactsProcessor.java

License:Open Source License

private final Collection<? extends URL> gatherArtifactUrls(final MavenProject project,
        final Collection<? extends Artifact> artifacts, final Log log) throws ArtifactsProcessingException {
    Collection<URL> returnValue = null;
    if (artifacts != null && !artifacts.isEmpty()) {
        final Collection<? extends String> names = this.getChangeLogResourceNames();
        if (names != null && !names.isEmpty()) {
            for (final Artifact artifact : artifacts) {
                if (artifact != null && artifact.isResolved()
                        && (project == null || !artifact.equals(project.getArtifact()))) {
                    final File artifactFile = artifact.getFile();
                    if (artifactFile != null && artifactFile.canRead()) {
                        for (final String name : names) {
                            if (name != null) {
                                URL url = null;
                                try {
                                    url = artifactFile.toURI().toURL();
                                } catch (final MalformedURLException wrapMe) {
                                    throw new ArtifactsProcessingException(wrapMe);
                                }/*from   w ww . j  a  va2  s . c om*/
                                final URLClassLoader loader = new URLClassLoader(new URL[] { url },
                                        Thread.currentThread().getContextClassLoader());
                                final URL jarUrlToChangeLog = loader.getResource(name);
                                if (jarUrlToChangeLog != null) {
                                    if (returnValue == null) {
                                        returnValue = new ArrayList<URL>(artifacts.size() * names.size());
                                    }
                                    returnValue.add(jarUrlToChangeLog);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return returnValue;
}

From source file:com.tenderowls.opensource.haxemojos.components.NativeBootstrap.java

License:Apache License

private Artifact resolveArtifact(Artifact artifact, List<ArtifactRepository> artifactRepositories)
        throws Exception {
    if (artifact.isResolved() || artifact.getFile() != null)
        return artifact;

    ArtifactResolutionRequest request = new ArtifactResolutionRequest();

    request.setArtifact(artifact);/*w  w w  .jav  a2 s  . c  o  m*/
    request.setLocalRepository(localRepository);
    request.setRemoteRepositories(artifactRepositories);
    ArtifactResolutionResult resolutionResult = repositorySystem.resolve(request);

    if (!resolutionResult.isSuccess()) {
        if (artifact.getType().equals(TGZ)) {
            artifact = repositorySystem.createArtifactWithClassifier(artifact.getGroupId(),
                    artifact.getArtifactId(), artifact.getVersion(), TARGZ, artifact.getClassifier());
            request = new ArtifactResolutionRequest();
            request.setArtifact(artifact);
            request.setLocalRepository(localRepository);
            request.setRemoteRepositories(project.getRemoteArtifactRepositories());
            resolutionResult = repositorySystem.resolve(request);
            if (resolutionResult.isSuccess()) {
                return artifact;
            }
        }
        String message = "Failed to resolve artifact " + artifact;
        throw new Exception(message);
    }

    return artifact;
}

From source file:com.vecna.maven.artifact.ArtifactLocationMojo.java

License:Apache License

/**
 * {@inheritDoc}//from  w w  w .ja  va  2  s  . c om
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    for (Object artifactObj : project.getDependencyArtifacts()) {
        Artifact artifact = (Artifact) artifactObj;
        String key = artifact.getGroupId() + ":" + artifact.getArtifactId();
        String property = artifacts.getProperty(key);
        if (property != null) {
            if (!artifact.isResolved()) {
                getLog().info("artifact " + artifact + " is not resolved yet");
                try {
                    resolver.resolve(artifact, remoteRepos, local);
                } catch (ArtifactNotFoundException e) {
                    throw new MojoExecutionException("can't resolve artifact", e);
                } catch (ArtifactResolutionException e) {
                    throw new MojoExecutionException("can't resolve artifact", e);
                }
            }
            String path = artifact.getFile().getAbsolutePath();
            getLog().info("setting project." + property + " to " + path);
            project.getProperties().setProperty(property, path);
        }
    }
}

From source file:lu.softec.maven.mavenizer.mavenfile.internal.DefaultMavenFileFactory.java

License:Open Source License

public MavenFile getMavenFile(File libfile, String groupId, String artifactId, String version,
        String classifier, MavenFileSet deps, ArtifactRepository repository, List remoteRepositories)
        throws InvalidMavenCoordinatesException, ArtifactResolutionException, ArtifactNotFoundException {
    File file = libfile;/*from   w ww  .ja  v a  2s .com*/

    // If no local file is provided, try to resolve missing artifact from local or remote repositories
    if (file == null) {
        if (repository == null) {
            return null;
        }
        Artifact artifact = artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, "jar",
                classifier);

        if (!artifact.isResolved() && remoteRepositories != null) {
            artifactResolver.resolve(artifact, remoteRepositories, repository);
        }
        file = artifact.getFile();

        if (file == null) {
            // Should never happen
            throw new ArtifactNotFoundException("No file available after artifact resolution", artifact);
        }
    }

    // If maven file already exists, than check it for consistencies and return the existing one
    if (mavenFiles.containsKey(file)) {
        InternalMavenFile mvnFile = (InternalMavenFile) mavenFiles.get(file);
        if (!StringUtils.equals(mvnFile.getGroupId(), groupId)
                || !StringUtils.equals(mvnFile.getArtifactId(), artifactId)
                || !StringUtils.equals(mvnFile.getVersion(), version)
                || !StringUtils.equals(mvnFile.getClassifier(), classifier) || (deps != null
                        && mvnFile.getDependencies().size() != 0 && !deps.equals(mvnFile.getDependencies()))) {
            throw new IllegalArgumentException(
                    "The instance requested mismatch with a previously existing instance for file "
                            + file.getAbsolutePath());
        }

        if (deps != null && mvnFile.getDependencies().size() == 0) {
            mvnFile.setDependencies(deps);
        }

        return mvnFile;
    }

    // Create a new maven file instance
    MavenFile mvnFile = new InternalMavenFile(file, groupId, artifactId, version, classifier, deps);

    // If the file has been provided, ensure proper maven coordinates has been used
    if (libfile != null) {
        validateArtifactInformation(mvnFile);
    }

    // Remember this new instance for future request
    mavenFiles.put(file, mvnFile);
    return mvnFile;
}

From source file:net.flexmojos.oss.plugin.war.CopyMojo.java

License:Open Source License

public Artifact resolve(String groupId, String artifactId, String version, String classifier, String type)
        throws RuntimeMavenResolutionException {
    Artifact artifact = repositorySystem.createArtifactWithClassifier(groupId, artifactId, version, type,
            classifier);/*  w  ww.ja  v  a  2 s  .c om*/
    if (!artifact.isResolved()) {
        ArtifactResolutionRequest req = new ArtifactResolutionRequest();
        req.setArtifact(artifact);
        req.setLocalRepository(localRepository);
        req.setRemoteRepositories(remoteRepositories);
        ArtifactResolutionResult res = repositorySystem.resolve(req);
        if (!res.isSuccess()) {
            if (getLog().isDebugEnabled()) {
                for (Exception e : res.getExceptions()) {
                    getLog().error(e);
                }
            }
            throw new RuntimeMavenResolutionException("Failed to resolve artifact " + artifact, res, artifact);
        }
    }
    return artifact;
}

From source file:npanday.plugin.azure.ResolveWorkerRoleFilesMojo.java

License:Apache License

private void unpack(Artifact artifact) throws MojoFailureException {
    File targetDirectory = new File(PathUtil.getPreparedPackageFolder(project), artifact.getArtifactId());
    try {/* w w w .ja v a  2s . c  o  m*/
        if (!artifact.isResolved()) {
            throw new MojoFailureException(
                    "NPANDAY-131-000: The artifact should already have been resolved: " + artifact);
        }

        final File packageSource = artifact.getFile();
        assert packageSource != null : "package source should not be null here";
        getLog().info("NPANDAY-131-002: Unpacking worker role " + artifact.getArtifactId() + " from "
                + packageSource + " " + "to " + targetDirectory);

        // unarchiver expects the dir to be there
        targetDirectory.mkdirs();

        unarchiver.setSourceFile(packageSource);
        unarchiver.setDestDirectory(targetDirectory);
        final IncludeExcludeFileSelector selector = new IncludeExcludeFileSelector();
        // TODO: quick hack for excluding service runtime in worker roles
        selector.setExcludes(new String[] { "Microsoft.WindowsAzure.ServiceRuntime.dll" });
        unarchiver.setFileSelectors(new FileSelector[] { selector });
        unarchiver.extract();

        if (targetDirectory.listFiles().length == 0) {
            throw new MojoFailureException(
                    "NPANDAY-131-003: Wasn't able to unpack worker role " + artifact.getArtifactId());
        }
    } catch (ArchiverException e) {
        throw new MojoFailureException(
                "NPANDAY-131-001: Unable to unpack worker role from artifact: " + artifact);
    }
}