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

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

Introduction

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

Prototype

void selectVersion(String version);

Source Link

Usage

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

private void recurse(ResolutionNode node, Map resolvedArtifacts, Map managedVersions,
        ArtifactRepository localRepository, List remoteRepositories, ArtifactMetadataSource source,
        ArtifactFilter filter, List listeners)
        throws CyclicDependencyException, ArtifactResolutionException, OverConstrainedVersionException {
    fireEvent(ResolutionListener.TEST_ARTIFACT, listeners, node);

    // TODO: use as a conflict resolver
    Object key = node.getKey();//from  www  .ja  v  a  2 s. co m
    if (managedVersions.containsKey(key)) {
        Artifact artifact = (Artifact) managedVersions.get(key);
        fireEvent(ResolutionListener.MANAGE_ARTIFACT, listeners, node, artifact);
        if (artifact.getVersion() != null) {
            node.getArtifact().setVersion(artifact.getVersion());
        }
        if (artifact.getScope() != null) {
            node.getArtifact().setScope(artifact.getScope());
        }
    }

    List previousNodes = (List) resolvedArtifacts.get(key);
    if (previousNodes != null) {
        node = checkPreviousNodes(node, listeners, previousNodes);
    } else {
        previousNodes = new ArrayList();
        resolvedArtifacts.put(key, previousNodes);
    }
    previousNodes.add(node);

    if (node.isActive()) {
        fireEvent(ResolutionListener.INCLUDE_ARTIFACT, listeners, node);
    }

    // don't pull in the transitive deps of a system-scoped dependency.
    if (node.isActive() && !Artifact.SCOPE_SYSTEM.equals(node.getArtifact().getScope())) {
        fireEvent(ResolutionListener.PROCESS_CHILDREN, listeners, node);
        for (Iterator i = node.getChildrenIterator(); i.hasNext();) {
            ResolutionNode child = (ResolutionNode) i.next();
            // We leave in optional ones, but don't pick up its dependencies
            if (!child.isResolved() && (!child.getArtifact().isOptional() || child.isChildOfRootNode())) {
                Artifact artifact = child.getArtifact();
                try {
                    if (artifact.getVersion() == null) {
                        // set the recommended version
                        // TODO: maybe its better to just pass the range
                        // through to retrieval and use a transformation?
                        ArtifactVersion version;
                        version = getArtifactVersion(localRepository, remoteRepositories, source, artifact);

                        artifact.selectVersion(version.toString());
                        fireEvent(ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, child);
                    }

                    ResolutionGroup rGroup = source.retrieve(artifact, localRepository, remoteRepositories);

                    // TODO might be better to have source.retreive() throw
                    // a specific exception for this situation
                    // and catch here rather than have it return null
                    if (rGroup == null) {
                        // relocated dependency artifact is declared
                        // excluded, no need to add and recurse further
                        continue;
                    }

                    child.addDependencies(rGroup.getArtifacts(), rGroup.getResolutionRepositories(), filter);
                } catch (CyclicDependencyException e) {
                    // would like to throw this, but we have crappy stuff in
                    // the repo

                    fireEvent(ResolutionListener.OMIT_FOR_CYCLE, listeners,
                            new ResolutionNode(e.getArtifact(), remoteRepositories, child));
                } catch (ArtifactMetadataRetrievalException e) {
                    artifact.setDependencyTrail(node.getDependencyTrail());
                    throw new ArtifactResolutionException(
                            "Unable to get dependency information: " + e.getMessage(), artifact, e);
                }

                recurse(child, resolvedArtifacts, managedVersions, localRepository, remoteRepositories, source,
                        filter, listeners);
            }
        }
        fireEvent(ResolutionListener.FINISH_PROCESSING_CHILDREN, listeners, node);
    }
}

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

private ResolutionNode checkPreviousNodes(ResolutionNode node, List listeners, List previousNodes)
        throws OverConstrainedVersionException {
    for (Iterator i = previousNodes.iterator(); i.hasNext();) {
        ResolutionNode previous = (ResolutionNode) i.next();
        if (previous.isActive()) {
            // Version mediation
            VersionRange previousRange = previous.getArtifact().getVersionRange();
            VersionRange currentRange = node.getArtifact().getVersionRange();
            // TODO: why do we force the version on it? what if they
            // don't match?
            if (previousRange == null) {
                // version was already resolved
                node.getArtifact().setVersion(previous.getArtifact().getVersion());
            } else if (currentRange == null) {
                // version was already resolved
                previous.getArtifact().setVersion(node.getArtifact().getVersion());
            } else {
                // TODO: shouldn't need to double up on this work, only
                // done for simplicity of handling recommended
                // version but the restriction is identical
                VersionRange newRange = previousRange.restrict(currentRange);
                // TODO: ick. this forces the OCE that should have come
                // from the previous call. It is still correct
                if (newRange.isSelectedVersionKnown(previous.getArtifact())) {
                    fireEvent(ResolutionListener.RESTRICT_RANGE, listeners, node, previous.getArtifact(),
                            newRange);//from  w  w  w  .  j a va2 s  .  c  o m
                }
                previous.getArtifact().setVersionRange(newRange);
                node.getArtifact().setVersionRange(currentRange.restrict(previousRange));

                // Select an appropriate available version from the (now
                // restricted) range
                // Note this version was selected before to get the
                // appropriate POM
                // But it was reset by the call to setVersionRange on
                // restricting the version
                ResolutionNode[] resetNodes = { previous, node };
                for (int j = 0; j < 2; j++) {
                    Artifact resetArtifact = resetNodes[j].getArtifact();
                    if (resetArtifact.getVersion() == null && resetArtifact.getVersionRange() != null
                            && resetArtifact.getAvailableVersions() != null) {

                        resetArtifact.selectVersion(resetArtifact.getVersionRange()
                                .matchVersion(resetArtifact.getAvailableVersions()).toString());
                        fireEvent(ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, resetNodes[j]);
                    }
                }
            }

            // Conflict Resolution
            // TODO: use as conflict resolver(s), chain

            // TODO: should this be part of mediation?
            // previous one is more dominant
            if (previous.getDepth() <= node.getDepth()) {
                checkScopeUpdate(node, previous, listeners);
            } else {
                checkScopeUpdate(previous, node, listeners);
            }

            if (previous.getDepth() <= node.getDepth()) {
                // previous was nearer
                fireEvent(ResolutionListener.OMIT_FOR_NEARER, listeners, node, previous.getArtifact());
                node.disable();
                node = previous;
            } else {
                fireEvent(ResolutionListener.OMIT_FOR_NEARER, listeners, previous, node.getArtifact());
                previous.disable();
            }
        }
    }
    return node;
}

From source file:org.apache.felix.bundleplugin.baseline.AbstractBaselinePlugin.java

License:Apache License

private Artifact getPreviousArtifact() throws MojoFailureException, MojoExecutionException {
    // Find the previous version JAR and resolve it, and it's dependencies
    final VersionRange range;
    try {// www  .j a va  2 s .  c om
        range = VersionRange.createFromVersionSpec(comparisonVersion);
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoFailureException("Invalid comparison version: " + e.getMessage());
    }

    final Artifact previousArtifact;
    try {
        previousArtifact = factory.createDependencyArtifact(comparisonGroupId, comparisonArtifactId, range,
                comparisonPackaging, comparisonClassifier, Artifact.SCOPE_COMPILE);

        if (!previousArtifact.getVersionRange().isSelectedVersionKnown(previousArtifact)) {
            getLog().debug("Searching for versions in range: " + previousArtifact.getVersionRange());
            @SuppressWarnings("unchecked")
            // type is konwn
            List<ArtifactVersion> availableVersions = metadataSource.retrieveAvailableVersions(previousArtifact,
                    session.getLocalRepository(), project.getRemoteArtifactRepositories());
            filterSnapshots(availableVersions);
            ArtifactVersion version = range.matchVersion(availableVersions);
            if (version != null) {
                previousArtifact.selectVersion(version.toString());
            }
        }
    } catch (OverConstrainedVersionException ocve) {
        throw new MojoFailureException("Invalid comparison version: " + ocve.getMessage());
    } catch (ArtifactMetadataRetrievalException amre) {
        throw new MojoExecutionException("Error determining previous version: " + amre.getMessage(), amre);
    }

    if (previousArtifact.getVersion() == null) {
        getLog().info("Unable to find a previous version of the project in the repository");
        return null;
    }

    try {
        resolver.resolve(previousArtifact, project.getRemoteArtifactRepositories(),
                session.getLocalRepository());
    } catch (ArtifactResolutionException are) {
        throw new MojoExecutionException(
                "Artifact " + previousArtifact + " cannot be resolved : " + are.getMessage(), are);
    } catch (ArtifactNotFoundException anfe) {
        throw new MojoExecutionException(
                "Artifact " + previousArtifact + " does not exist on local/remote repositories", anfe);
    }

    return previousArtifact;
}

From source file:org.codehaus.mojo.clirr.AbstractClirrMojo.java

License:Apache License

private Artifact getComparisonArtifact() throws MojoFailureException, MojoExecutionException {
    // Find the previous version JAR and resolve it, and it's dependencies
    VersionRange range;//  w  w  w. java2  s.  com
    try {
        range = VersionRange.createFromVersionSpec(comparisonVersion);
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoFailureException("Invalid comparison version: " + e.getMessage());
    }

    Artifact previousArtifact;
    try {
        previousArtifact = factory.createDependencyArtifact(project.getGroupId(), project.getArtifactId(),
                range, project.getPackaging(), null, Artifact.SCOPE_COMPILE);

        if (!previousArtifact.getVersionRange().isSelectedVersionKnown(previousArtifact)) {
            getLog().debug("Searching for versions in range: " + previousArtifact.getVersionRange());
            List availableVersions = metadataSource.retrieveAvailableVersions(previousArtifact, localRepository,
                    project.getRemoteArtifactRepositories());
            filterSnapshots(availableVersions);
            ArtifactVersion version = range.matchVersion(availableVersions);
            if (version != null) {
                previousArtifact.selectVersion(version.toString());
            }
        }
    } catch (OverConstrainedVersionException e1) {
        throw new MojoFailureException("Invalid comparison version: " + e1.getMessage());
    } catch (ArtifactMetadataRetrievalException e11) {
        throw new MojoExecutionException("Error determining previous version: " + e11.getMessage(), e11);
    }

    if (previousArtifact.getVersion() == null) {
        getLog().info("Unable to find a previous version of the project in the repository");
    }

    return previousArtifact;
}

From source file:org.eclipse.che.maven.CheArtifactResolver.java

License:Apache License

private boolean isModule(Artifact artifact) {
    MavenWorkspaceCache cache = workspaceCache;
    if (cache == null) {
        return false;
    }/*from  w  ww.  j a va  2 s .  c om*/
    Entry entry = cache
            .findEntry(new MavenKey(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
    if (entry == null) {
        return false;
    }
    artifact.setResolved(true);
    artifact.setFile(entry.getFile(artifact.getType()));
    artifact.selectVersion(entry.getKey().getVersion());
    return true;
}

From source file:org.eclipse.che.maven.CheArtifactResolver.java

License:Apache License

private void resolveOrig(Artifact artifact, List<ArtifactRepository> remoteRepositories,
        RepositorySystemSession session) throws ArtifactResolutionException, ArtifactNotFoundException {
    if (artifact == null) {
        return;//from   w w  w. java 2  s  .  co m
    }

    if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
        File systemFile = artifact.getFile();

        if (systemFile == null) {
            throw new ArtifactNotFoundException("System artifact: " + artifact + " has no file attached",
                    artifact);
        }

        if (!systemFile.exists()) {
            throw new ArtifactNotFoundException(
                    "System artifact: " + artifact + " not found in path: " + systemFile, artifact);
        }

        if (!systemFile.isFile()) {
            throw new ArtifactNotFoundException(
                    "System artifact: " + artifact + " is not a file: " + systemFile, artifact);
        }

        artifact.setResolved(true);

        return;
    }

    if (!artifact.isResolved()) {
        ArtifactResult result;

        try {
            ArtifactRequest artifactRequest = new ArtifactRequest();
            artifactRequest.setArtifact(RepositoryUtils.toArtifact(artifact));
            artifactRequest.setRepositories(RepositoryUtils.toRepos(remoteRepositories));

            // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
            LocalRepositoryManager lrm = session.getLocalRepositoryManager();
            String path = lrm.getPathForLocalArtifact(artifactRequest.getArtifact());
            artifact.setFile(new File(lrm.getRepository().getBasedir(), path));

            result = repoSystem.resolveArtifact(session, artifactRequest);
        } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) {
            if (e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException) {
                throw new ArtifactNotFoundException(e.getMessage(), artifact.getGroupId(),
                        artifact.getArtifactId(), artifact.getVersion(), artifact.getType(),
                        artifact.getClassifier(), remoteRepositories, artifact.getDownloadUrl(),
                        artifact.getDependencyTrail(), e);
            } else {
                throw new ArtifactResolutionException(e.getMessage(), artifact, remoteRepositories, e);
            }
        }

        artifact.selectVersion(result.getArtifact().getVersion());
        artifact.setFile(result.getArtifact().getFile());
        artifact.setResolved(true);

        if (artifact.isSnapshot()) {
            Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(artifact.getVersion());
            if (matcher.matches()) {
                Snapshot snapshot = new Snapshot();
                snapshot.setTimestamp(matcher.group(2));
                try {
                    snapshot.setBuildNumber(Integer.parseInt(matcher.group(3)));
                    artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot));
                } catch (NumberFormatException e) {
                    logger.warn("Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.eclipse.m2e.core.internal.embedder.MavenImpl.java

License:Open Source License

public Artifact resolve(final Artifact artifact, List<ArtifactRepository> remoteRepositories,
        IProgressMonitor monitor) throws CoreException {
    if (remoteRepositories == null) {
        try {/*from w w  w. j  a v  a  2 s.  com*/
            remoteRepositories = getArtifactRepositories();
        } catch (CoreException e) {
            // we've tried
            remoteRepositories = Collections.emptyList();
        }
    }
    final List<ArtifactRepository> _remoteRepositories = remoteRepositories;

    return context().execute(new ICallable<Artifact>() {
        public Artifact call(IMavenExecutionContext context, IProgressMonitor monitor) throws CoreException {
            org.sonatype.aether.RepositorySystem repoSystem = lookup(
                    org.sonatype.aether.RepositorySystem.class);

            ArtifactRequest request = new ArtifactRequest();
            request.setArtifact(RepositoryUtils.toArtifact(artifact));
            request.setRepositories(RepositoryUtils.toRepos(_remoteRepositories));

            ArtifactResult result;
            try {
                result = repoSystem.resolveArtifact(context.getRepositorySession(), request);
            } catch (ArtifactResolutionException ex) {
                result = ex.getResults().get(0);
            }

            setLastUpdated(context.getLocalRepository(), _remoteRepositories, artifact);

            if (result.isResolved()) {
                artifact.selectVersion(result.getArtifact().getVersion());
                artifact.setFile(result.getArtifact().getFile());
                artifact.setResolved(true);
            } else {
                ArrayList<IStatus> members = new ArrayList<IStatus>();
                for (Exception e : result.getExceptions()) {
                    if (!(e instanceof ArtifactNotFoundException)) {
                        members.add(
                                new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1, e.getMessage(), e));
                    }
                }
                if (members.isEmpty()) {
                    members.add(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1,
                            NLS.bind(Messages.MavenImpl_error_missing, artifact), null));
                }
                IStatus[] newMembers = members.toArray(new IStatus[members.size()]);
                throw new CoreException(new MultiStatus(IMavenConstants.PLUGIN_ID, -1, newMembers,
                        NLS.bind(Messages.MavenImpl_error_resolve, artifact.toString()), null));
            }

            return artifact;
        }
    }, monitor);
}

From source file:org.jetbrains.idea.maven.server.embedder.CustomArtifactResolver.java

License:Apache License

private boolean resolveAsModule(Artifact a) {
    // method is called from different threads, so we have to copy the reference so ensure there is no race conditions.
    MavenWorkspaceMap map = myWorkspaceMap;
    if (map == null)
        return false;

    MavenWorkspaceMap.Data resolved = map.findFileAndOriginalId(Maven2ModelConverter.createMavenId(a));
    if (resolved == null)
        return false;

    a.setResolved(true);//from   w ww  . java2  s . co  m
    a.setFile(resolved.getFile(a.getType()));
    a.selectVersion(resolved.originalId.getVersion());

    return true;
}

From source file:org.jetbrains.idea.maven.server.embedder.CustomMaven32ArtifactResolver.java

License:Apache License

private void resolveOld(Artifact artifact, List<ArtifactRepository> remoteRepositories,
        RepositorySystemSession session) throws ArtifactResolutionException, ArtifactNotFoundException {
    if (artifact == null) {
        return;//from  w  w  w  . j  a va2s . c o m
    }

    if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
        File systemFile = artifact.getFile();

        if (systemFile == null) {
            throw new ArtifactNotFoundException("System artifact: " + artifact + " has no file attached",
                    artifact);
        }

        if (!systemFile.exists()) {
            throw new ArtifactNotFoundException(
                    "System artifact: " + artifact + " not found in path: " + systemFile, artifact);
        }

        if (!systemFile.isFile()) {
            throw new ArtifactNotFoundException(
                    "System artifact: " + artifact + " is not a file: " + systemFile, artifact);
        }

        artifact.setResolved(true);

        return;
    }

    if (!artifact.isResolved()) {
        ArtifactResult result;

        try {
            ArtifactRequest artifactRequest = new ArtifactRequest();
            artifactRequest.setArtifact(RepositoryUtils.toArtifact(artifact));
            artifactRequest.setRepositories(RepositoryUtils.toRepos(remoteRepositories));

            // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
            LocalRepositoryManager lrm = session.getLocalRepositoryManager();
            String path = lrm.getPathForLocalArtifact(artifactRequest.getArtifact());
            artifact.setFile(new File(lrm.getRepository().getBasedir(), path));

            result = repoSystem.resolveArtifact(session, artifactRequest);
        } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) {
            if (e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException) {
                throw new ArtifactNotFoundException(e.getMessage(), artifact.getGroupId(),
                        artifact.getArtifactId(), artifact.getVersion(), artifact.getType(),
                        artifact.getClassifier(), remoteRepositories, artifact.getDownloadUrl(),
                        artifact.getDependencyTrail(), e);
            } else {
                throw new ArtifactResolutionException(e.getMessage(), artifact, remoteRepositories, e);
            }
        }

        artifact.selectVersion(result.getArtifact().getVersion());
        artifact.setFile(result.getArtifact().getFile());
        artifact.setResolved(true);

        if (artifact.isSnapshot()) {
            Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(artifact.getVersion());
            if (matcher.matches()) {
                Snapshot snapshot = new Snapshot();
                snapshot.setTimestamp(matcher.group(2));
                try {
                    snapshot.setBuildNumber(Integer.parseInt(matcher.group(3)));
                    artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot));
                } catch (NumberFormatException e) {
                    logger.warn("Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.jetbrains.idea.maven.server.embedder.CustomMaven32ArtifactResolver.java

License:Apache License

private boolean resolveAsModule(Artifact a) {
    // method is called from different threads, so we have to copy the reference so ensure there is no race conditions.
    MavenWorkspaceMap map = myWorkspaceMap;
    if (map == null)
        return false;

    MavenWorkspaceMap.Data resolved = map.findFileAndOriginalId(MavenModelConverter.createMavenId(a));
    if (resolved == null)
        return false;

    a.setResolved(true);//ww  w . j a  v  a  2 s.  c  o  m
    a.setFile(resolved.getFile(a.getType()));
    a.selectVersion(resolved.originalId.getVersion());

    return true;
}