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

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

Introduction

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

Prototype

ArtifactVersion getSelectedVersion() throws OverConstrainedVersionException;

Source Link

Usage

From source file:com.actility.maven.plugin.cocoon.GenerateKfCocoonMojo.java

License:Apache License

private void buildFirmwareManifest(List<FirmwareEntryConfiguration> firmwareEntries, File destDir,
        String firmwareQualifier) throws MojoExecutionException {
    File firmwareManifestFile = new File(destDir, "firmware-manifest.properties");
    BufferedWriter out = null;/*from  w  w w .j  a v  a  2  s . c om*/
    int index = 0;
    try {

        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(firmwareManifestFile), "ASCII"));

        out.write("firmware.versionPrefix=");
        out.write(versionPrefix);
        out.write("\n");
        out.write("firmware.versionNumber=");
        Artifact artifact = project.getArtifact();
        out.write(MavenUtils.getOSGiVersion(artifact));
        // Add firmware extra qualifier to firmware.versionNumber
        if (firmwareQualifier != null) {
            if (StringUtils.isNotEmpty(artifact.getSelectedVersion().getQualifier())) {
                out.write("_");
            } else {
                out.write(".");
            }
            out.write(firmwareQualifier);
        }

        out.write("\n");
        out.write("\n");

        // part.{index}.id=
        // part.{index}.namespace=
        // part.{index}.name=
        // part.{index}.version=
        // part.{index}.fullname=
        // part.{index}.installationType=
        for (FirmwareEntryConfiguration firmwareEntry : firmwareEntries) {
            if (!firmwareEntry.isOneTime()) {
                ++index;
                String prefix = "";
                if (firmwareEntry.isComment()) {
                    prefix += "#";
                }
                prefix += "part." + String.valueOf(index) + ".";

                out.write(prefix + "id=");
                out.write(firmwareEntry.getId());
                out.write("\n");
                out.write(prefix + "namespace=");
                out.write(firmwareEntry.getNamespace());
                out.write("\n");
                out.write(prefix + "name=");
                out.write(firmwareEntry.getName());
                out.write("\n");
                out.write(prefix + "version=");
                out.write(firmwareEntry.getVersion());
                out.write("\n");
                out.write(prefix + "fullname=");
                out.write(firmwareEntry.getDestFile());
                out.write("\n");
                out.write(prefix + "installationType=");
                out.write(firmwareEntry.getInstallationType());
                out.write("\n");
                out.write("\n");
            }
        }
        out.write("\n");
    } catch (IOException e) {
        throw new MojoExecutionException("IO problem while generating firmware-manifest.properties file", e);
    } catch (OverConstrainedVersionException e) {
        throw new MojoExecutionException("Failed to retrieve project artifact version", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            throw new MojoExecutionException("IO problem while closing firmware-manifest.properties file", e);
        }
    }
}

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

License:Apache License

private ArtifactVersion getArtifactVersion(ArtifactRepository localRepository, List remoteRepositories,
        ArtifactMetadataSource source, Artifact artifact)
        throws OverConstrainedVersionException, ArtifactMetadataRetrievalException {
    ArtifactVersion version;//from www  .  j a  v  a2 s.c  o  m
    if (!artifact.isSelectedVersionKnown()) {
        List versions = artifact.getAvailableVersions();
        if (versions == null) {
            versions = source.retrieveAvailableVersions(artifact, localRepository, remoteRepositories);
            artifact.setAvailableVersions(versions);
        }

        VersionRange versionRange = artifact.getVersionRange();

        version = versionRange.matchVersion(versions);

        if (version == null) {
            if (versions.isEmpty()) {
                throw new OverConstrainedVersionException(
                        "No versions are present in the repository for the artifact with a range "
                                + versionRange,
                        artifact, remoteRepositories);
            } else {
                throw new OverConstrainedVersionException(
                        "Couldn't find a version in " + versions + " to match range " + versionRange, artifact,
                        remoteRepositories);
            }
        }
    } else {
        version = artifact.getSelectedVersion();
    }
    return version;
}

From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

License:Apache License

/**
 * Create a version resolution for the given dependency and artifact.
 *//*  w  ww .j a va2 s.co  m*/
private VersionResolution resolveVersion(Dependency dependency, Artifact artifact, String artifactName,
        final boolean directArtifact) {
    VersionResolution resolution = null;

    try {
        // Build a version from the artifact that was resolved.
        ArtifactVersion resolvedVersion = artifact.getSelectedVersion();

        if (resolvedVersion == null) {
            resolvedVersion = new DefaultArtifactVersion(artifact.getVersion());
        }

        // versionRange represents the versions that will satisfy the dependency.
        VersionRange versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
        // expectedVersion is the version declared in the dependency.
        ArtifactVersion expectedVersion = versionRange.getRecommendedVersion();

        if (expectedVersion == null) {
            // Fall back to the artifact version if it fits.
            if (versionRange.containsVersion(resolvedVersion)) {
                expectedVersion = resolvedVersion;
            } else {
                LOG.error(
                        "Cannot determine the recommended version of dependency '{}'; its version specification is '{}', and the resolved version is '{}'.",
                        new Object[] { artifactName, dependency.getVersion(), resolvedVersion.toString() });
                return null;
            }
        }

        // Build internal versions
        final Version resolvedVersionObj = new Version(resolvedVersion.toString());
        final Version depVersionObj = new Version(versionRange.toString(), expectedVersion.toString());

        resolution = new VersionResolution(artifactName, artifactName, depVersionObj, resolvedVersionObj,
                directArtifact);

        if (!isExcluded(artifact, depVersionObj, resolvedVersionObj)) {
            final Strategy strategy = findStrategy(resolution);

            if (!(versionRange.containsVersion(resolvedVersion)
                    && strategy.isCompatible(resolvedVersionObj, depVersionObj))) {
                resolution.setConflict(true);
            }
        }
    } catch (InvalidVersionSpecificationException ex) {
        LOG.warn("Could not parse the version specification of an artifact", ex);
    } catch (OverConstrainedVersionException ex) {
        LOG.warn("Could not resolve an artifact", ex);
    }
    return resolution;
}

From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

License:Apache License

/**
 * Return a version object for an Artifact.
 */// ww  w  .  j  a v  a  2 s.  c om
private Version getVersion(Artifact artifact) throws OverConstrainedVersionException {
    Version version = null;

    if (artifact != null) {
        if ((artifact.getVersionRange() != null) && (artifact.getSelectedVersion() != null)) {
            version = new Version(artifact.getVersionRange().toString(),
                    artifact.getSelectedVersion().toString());
        } else {
            version = new Version(artifact.getVersion());
        }
    }
    return version;
}

From source file:com.ning.maven.plugins.duplicatefinder.DependencyWrapper.java

License:Apache License

public boolean matches(Artifact artifact) {
    ArtifactVersion version;/*from   w  ww.  j av a  2s . c  om*/

    try {
        if (artifact.getVersionRange() != null) {
            version = artifact.getSelectedVersion();
        } else {
            version = new DefaultArtifactVersion(artifact.getVersion());
        }
    } catch (OverConstrainedVersionException ex) {
        return false;
    }

    return StringUtils.equals(dependency.getGroupId(), artifact.getGroupId())
            && StringUtils.equals(dependency.getArtifactId(), artifact.getArtifactId())
            && StringUtils.equals(StringUtils.defaultIfEmpty(dependency.getType(), "jar"),
                    StringUtils.defaultIfEmpty(artifact.getType(), "jar"))
            && StringUtils.equals(dependency.getClassifier(), artifact.getClassifier())
            && (versionRange == null || versionRange.containsVersion(version)
                    || StringUtils.equals(artifact.getVersion(), dependency.getVersion()));
}

From source file:com.ning.maven.plugins.duplicatefinder.Exception.java

License:Apache License

private boolean currentProjectDependencyMatches(Artifact artifact, Artifact projectArtifact) {
    VersionRange versionRange = projectArtifact.getVersionRange();
    ArtifactVersion version;//w  w w  .ja  va2s  . com

    try {
        if (artifact.getVersionRange() != null) {
            version = artifact.getSelectedVersion();
        } else {
            version = new DefaultArtifactVersion(artifact.getVersion());
        }
    } catch (OverConstrainedVersionException ex) {
        return false;
    }

    return StringUtils.equals(projectArtifact.getGroupId(), artifact.getGroupId())
            && StringUtils.equals(projectArtifact.getArtifactId(), artifact.getArtifactId())
            && StringUtils.equals(StringUtils.defaultIfEmpty(projectArtifact.getType(), "jar"),
                    StringUtils.defaultIfEmpty(artifact.getType(), "jar"))
            && StringUtils.equals(projectArtifact.getClassifier(), artifact.getClassifier())
            && ((versionRange != null && versionRange.containsVersion(version))
                    || artifact.getVersion().equals(projectArtifact.getVersion()));
}

From source file:com.unibet.maven.DependencyMetadataGenerateMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Artifact artifact = project.getArtifact();
    List<ArtifactVersion> versions = new ArrayList<>(1);
    try {//from w  ww . ja v  a2  s .  c o m
        versions.add(artifact.getSelectedVersion());
    } catch (OverConstrainedVersionException e) {
        throw new MojoFailureException("Failed getting selected version for artifact " + artifact, e);
    }

    if (applyOnPreviousVersions) {
        // Enable both releases and snapshot repositories and always update the metadata
        for (ArtifactRepository repository : remoteRepositories) {
            repository.getReleases().setUpdatePolicy(UPDATE_POLICY_ALWAYS);
            repository.getReleases().setEnabled(true);
            repository.getSnapshots().setUpdatePolicy(UPDATE_POLICY_ALWAYS);
            repository.getSnapshots().setEnabled(true);
        }
        versions.addAll(getLowerVersions(artifact));
    }

    for (ArtifactVersion version : versions) {
        Artifact metadataArtifact = artifactFactory.createArtifactWithClassifier(artifact.getGroupId(),
                artifact.getArtifactId(), version.toString(), METADATA_ARTIFACT_TYPE,
                METADATA_ARTIFACT_CLASSIFIER);
        try {
            logger.debug("Resolving metadata artifact {} in {} and {}", metadataArtifact, remoteRepositories,
                    logger);
            resolver.resolve(metadataArtifact, remoteRepositories, localRepository);
            logger.info("Metadata artifact {} already exists. Skipping...", metadataArtifact);
        } catch (ArtifactResolutionException e) {
            throw new MojoExecutionException("Failed resolving metadata artifact " + metadataArtifact, e);
        } catch (ArtifactNotFoundException e) {
            logger.debug("Metadata artifact {} not found", metadataArtifact);

            String filename = project.getArtifactId() + "-" + version.toString() + "-"
                    + METADATA_ARTIFACT_CLASSIFIER + "." + METADATA_ARTIFACT_TYPE;
            File artifactFile = new File(project.getBuild().getDirectory() + File.separator + filename);

            Metadata metadata = new Metadata();
            metadata.formatVersion = this.formatVersion;
            metadata.message = this.message;
            metadata.fail = this.fail;

            new File(project.getBuild().getDirectory()).mkdirs();
            try {
                OBJECT_MAPPER.writeValue(artifactFile, metadata);
            } catch (IOException ioe) {
                throw new MojoFailureException("Failed creating metadata artifact file " + artifactFile, ioe);
            }
            project.addAttachedArtifact(metadataArtifact);
            logger.info("Metadata artifact generated: {}", artifactFile);
        }
    }
}

From source file:com.unibet.maven.DependencyMetadataGenerateMojo.java

License:Apache License

@SuppressWarnings("unchecked")
private List<ArtifactVersion> getLowerVersions(Artifact artifact) throws MojoExecutionException {
    List<ArtifactVersion> lowerVersions;
    try {/*from  w  w w  .  j  av a  2s  .  co m*/
        List<ArtifactVersion> versions = artifactMetadataSource.retrieveAvailableVersions(artifact,
                localRepository, remoteRepositories);
        lowerVersions = new ArrayList<>(versions.size());
        for (ArtifactVersion version : versions) {
            if (version.compareTo(artifact.getSelectedVersion()) < 0) {
                lowerVersions.add(version);
            }
        }
    } catch (OverConstrainedVersionException | ArtifactMetadataRetrievalException e) {
        throw new MojoExecutionException("Failed getting lower versions for " + artifact, e);
    }
    return lowerVersions;
}

From source file:de.tarent.maven.plugins.pkg.map.PackageMap.java

License:Open Source License

public void iterateDependencyArtifacts(Log l, Collection<Artifact> deps, Visitor v, boolean bundleNonExisting) {
    for (Iterator<Artifact> ite = deps.iterator(); ite.hasNext();) {
        Artifact a = ite.next();
        String aid = a.getArtifactId();

        // Bundle dependencies which have been explicitly
        // marked as such.
        if (bundleOverrides.contains(aid)) {
            v.bundle(a);/*from   w w w  . ja v a  2s.  co  m*/
            continue;
        }

        Entry e;
        try {
            e = mapping.getEntry(a.getGroupId(), aid, a.getSelectedVersion());
        } catch (OverConstrainedVersionException e1) {
            throw new IllegalStateException("Unable to retrieve selected artifact version.", e1);
        }
        // If a distro is explicitly declared to have no packages everything
        // will be bundled (without warning).
        if (mapping.hasNoPackages) {
            v.bundle(a);
        } else if (e == null) {
            // If a package as not been declared a warning reminds to fix
            // the
            // package map.
            l.warn(mapping.distro + " has no entry for: " + a);

            if (bundleNonExisting) {
                v.bundle(a);
            }
        } else if (e.bundleEntry) {
            // If a package is explicitly said to be bundled this will be
            // done
            // without warning.
            v.bundle(a);
        } else if (e.ignoreEntry) {
            // If a package is explicitly said to be ignored this will be
            // done without warning.
            l.debug("Ignoring entry '" + e.artifactSpec + "', ignoreEntry flag is set");
        } else {
            // Otherwise we have a plain dead easy Entry which needs to be
            // processed
            // somehow.
            v.visit(a, e);
        }
    }
}

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

License:Open Source License

/**
 * Builds the list artifacts./*  ww w  . ja  va2s .  com*/
 *
 * @param artifactsReturn the artifacts return
 * @param artifactsToCopy the artifacts to copy
 * @param artifactsToDelete the artifacts to delete
 * @throws MojoExecutionException the mojo execution exception
 */
private void buildListArtifacts(Set<Artifact> artifactsReturn, Set<Artifact> artifactsToCopy,
        Set<Artifact> artifactsToDelete) throws MojoExecutionException {
    getLog().info("Building lists of artifacts to copy and to remove");

    for (Artifact artifact : artifactsReturn) {
        boolean bIsInMultiProject = false;

        for (Artifact multiprojetArtifact : multiProjectArtifactsCopied) {
            // Check artifact ID
            if (artifact.getArtifactId().equals(multiprojetArtifact.getArtifactId())
                    && artifact.getGroupId().equals(multiprojetArtifact.getGroupId())) {
                //Workaround MAVENPLUGIN-33 - NullPointerException when doing multi-project with excluded dependencies
                //Some excluded artifacts are in the list but with a null VersionRange, which triggers an NPE in getSelectedVersion()..
                //Skip them because we want to exclude them anyway.
                if (artifact.getVersionRange() != null) {
                    // Compare version
                    try {
                        if (artifact.getSelectedVersion()
                                .compareTo(multiprojetArtifact.getSelectedVersion()) > 0) {
                            artifactsToDelete.add(multiprojetArtifact);
                        } else {
                            bIsInMultiProject = true;
                        }
                    } catch (OverConstrainedVersionException e) {
                        throw new MojoExecutionException("Error while removing comparing versions", e);
                    }
                }

                break;
            }
        }

        if (!bIsInMultiProject) {
            artifactsToCopy.add(artifact);
        }
    }

    multiProjectArtifactsCopied.removeAll(artifactsToDelete);
    multiProjectArtifactsCopied.addAll(artifactsToCopy);
}