Example usage for org.apache.maven.artifact.versioning VersionRange createFromVersionSpec

List of usage examples for org.apache.maven.artifact.versioning VersionRange createFromVersionSpec

Introduction

In this page you can find the example usage for org.apache.maven.artifact.versioning VersionRange createFromVersionSpec.

Prototype

public static VersionRange createFromVersionSpec(String spec) throws InvalidVersionSpecificationException 

Source Link

Document

Create a version range from a string representation

Some spec examples are:
  • 1.0 Version 1.0
  • [1.0,2.0) Versions 1.0 (included) to 2.0 (not included)
  • [1.0,2.0] Versions 1.0 to 2.0 (both included)
  • [1.5,) Versions 1.5 and higher
  • (,1.0],[1.2,) Versions up to 1.0 (included) and 1.2 or higher

Usage

From source file:com.googlecode.japi.checker.maven.plugin.BackwardCompatibilityCheckerMojo.java

License:Apache License

/**
 * Resolves the Artifact from the remote repository if necessary. If no version is specified, it will be retrieved
 * from the dependency list or from the DependencyManagement section of the pom.
 * //from  w w  w.  j  a v  a  2s.  c  o  m
 * @param artifactItem containing information about artifact from plugin configuration.
 * @return Artifact object representing the specified file.
 * @throws MojoExecutionException with a message if the version can't be found in DependencyManagement.
 */
protected void updateArtifact(ArtifactItem artifactItem) throws MojoExecutionException {

    if (artifactItem.getArtifact() != null) {
        return;
    }

    VersionRange vr;
    try {
        vr = VersionRange.createFromVersionSpec(artifactItem.getVersion());
    } catch (InvalidVersionSpecificationException e) {
        vr = VersionRange.createFromVersion(artifactItem.getVersion());
    }

    Artifact artifact = getFactory().createDependencyArtifact(artifactItem.getGroupId(),
            artifactItem.getArtifactId(), vr, artifactItem.getType(), null, Artifact.SCOPE_COMPILE);

    try {
        getResolver().resolve(artifact, remoteRepos, localRepository);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve artifact.", e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Unable to find artifact.", e);
    }

    artifactItem.setArtifact(artifact);
}

From source file:com.googlecode.jndiresources.install.JNDIInstall.java

License:Apache License

/**
 * Install the packages in application server.
 * //  w  w w.j  ava2s .  co m
 * @param params The parameters set.
 * 
 * @throws CommandLineException If error.
 * @throws IOException If error.
 * @throws ParserConfigurationException If error.
 * @throws SAXException If error.
 * @throws XPathExpressionException If error.
 * @throws TransformerException If error.
 * @throws InvalidVersionSpecificationException If version is invalid.
 * @throws URISyntaxException If target is not an URL.
 */
public JNDIInstall(final ParamsInstall params) throws CommandLineException, IOException, SAXException,
        ParserConfigurationException, XPathExpressionException, TransformerException,
        InvalidVersionSpecificationException, URISyntaxException {
    for (StringTokenizer tokens = new StringTokenizer(params.appsrv_, ","); tokens.hasMoreTokens();) {
        final String curappsrv = tokens.nextToken().trim();
        LOG.info("Profile " + curappsrv);
        packageDir_ = params.package_;
        srvapp_ = null;

        packageDir_ = new File(packageDir_).getCanonicalPath();
        if (params.version_ != null) {
            final File versionFile = new File(packageDir_, VERSIONS_XML);
            if (versionFile.canRead()) {
                final Document versionsDoc = XMLContext.DOC_BUILDER_FACTORY.newDocumentBuilder()
                        .parse(versionFile);

                // Find all resources groups, and associate an id
                final NodeList result = (NodeList) xpathVersion_.evaluate(versionsDoc, XPathConstants.NODESET);

                for (int i = 0; i < result.getLength(); ++i) {
                    final Node home = result.item(i);
                    final Node nameNode = home.getAttributes().getNamedItem("name");
                    if (curappsrv.equals(nameNode.getNodeValue())) {
                        Node versionsNode = home.getAttributes().getNamedItem("versions");
                        VersionRange range = VersionRange.createFromVersionSpec(versionsNode.getNodeValue());
                        if (range.containsVersion(params.version_)) {
                            srvapp_ = home.getAttributes().getNamedItem("target").getNodeValue();
                            break;
                        }
                    }
                }
                if (srvapp_ == null) {
                    throw new CommandLineException("Application server can't be found in versions.xml.");
                }

            } else if (params.version_ == null) {
                throw new CommandLineException("--version can't be set with this templates");
            }
        } else
            srvapp_ = curappsrv;

        initVariables(params.propertieslist_);
        prop_.putAll(params.cmdlineprop_);
        xslprop_ = params.cmdlinexslprop_;

        final ApplyInstall apply = new ApplyInstall();

        final File f = new File(packageDir_, srvapp_);
        if (!f.canRead())
            throw new CommandLineException(f + " not found. Update the --appsrv parameter or add a --version");
        final String[] targets = f.list();
        for (int i = 0; i < targets.length; ++i) {
            final String target = targets[i];
            if (!new File(packageDir_, srvapp_ + File.separatorChar + target).isDirectory())
                continue;
            String targetDir = (String) params.targetList_.get(target);
            if (targetDir == null) {
                throw new CommandLineException("--dest " + target + "=... must be set");
            }
            //            targetDir = new File(targetDir).getCanonicalFile().toURI().toURL().toExternalForm();
            targetDir = new File(targetDir).getAbsolutePath() + File.separator;
            File home = new File(packageDir_, srvapp_ + File.separatorChar + target).getCanonicalFile();
            if (home.canRead()) {
                LOG.info("Install to " + targetDir);
                apply.destination_ = targetDir;
                RecursiveFiles.recursiveFiles(home, ".", apply);
            }
        }
        if (tokens.hasMoreTokens())
            LOG.info(LINE);
    }
}

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  av a 2 s. c o  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.duplicatefinder.DependencyWrapper.java

License:Apache License

public DependencyWrapper(Dependency dependency) throws InvalidVersionSpecificationException {
    this.dependency = dependency;
    this.versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
}

From source file:com.redhat.rcm.maven.plugin.buildmetadata.util.ReportUtils.java

License:Apache License

/**
 * Returns a file reference to the default skin useful for rendering
 * standalone run reports.//from ww  w  .  j a  va2 s  .c o  m
 * <p>
 * Stolen from the changes plugin.
 * </p>
 *
 * @param project the project of the plugin that calls this method.
 * @param localRepository a reference to the local repository to reference to.
 * @param resolver to resolve the skin artifact.
 * @param factory to resolve dependencies.
 * @return a file reference to the default skin.
 * @throws MojoExecutionException if the skin artifact cannot be resolved.
 */
public static File getSkinArtifactFile(final MavenProject project, final ArtifactRepository localRepository,
        final ArtifactResolver resolver, final ArtifactFactory factory) throws MojoExecutionException {
    final Skin skin = Skin.getDefaultSkin();
    final String version = determineVersion(skin);
    try {
        final VersionRange versionSpec = VersionRange.createFromVersionSpec(version);
        final Artifact artifact = factory.createDependencyArtifact(skin.getGroupId(), skin.getArtifactId(),
                versionSpec, "jar", null, null);
        resolver.resolve(artifact, project.getRemoteArtifactRepositories(), localRepository);

        return artifact.getFile();
    } catch (final InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("The skin version '" + version + "' is not valid: " + e.getMessage(),
                e);
    } catch (final ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to find skin", e);
    } catch (final ArtifactNotFoundException e) {
        throw new MojoExecutionException("The skin does not exist: " + e.getMessage(), e);
    }
}

From source file:com.smartitengineering.cms.maven.tools.plugin.StartMojo.java

License:Open Source License

protected Artifact getArtifact(ArtifactItem item) {
    VersionRange vr;/*w  w w  . ja  v a  2s.com*/
    try {
        vr = VersionRange.createFromVersionSpec(item.getVersion());
    } catch (InvalidVersionSpecificationException e1) {
        vr = VersionRange.createFromVersion(item.getVersion());
    }
    final Artifact artifact;
    if (StringUtils.isBlank(item.getClassifier())) {
        artifact = factory.createDependencyArtifact(item.getGroupId(), item.getArtifactId(), vr, item.getType(),
                item.getClassifier(), Artifact.SCOPE_COMPILE);
    } else {
        artifact = factory.createDependencyArtifact(item.getGroupId(), item.getArtifactId(), vr, item.getType(),
                null, Artifact.SCOPE_COMPILE);
    }
    try {
        resolver.resolve(artifact, remoteRepos, local);
    } catch (ArtifactResolutionException ex) {
        throw new IllegalArgumentException(ex);
    } catch (ArtifactNotFoundException ex) {
        throw new IllegalArgumentException(ex);
    }
    return artifact;
}

From source file:de.mytoys.maven.plugins.debug.AbstractDebugMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    ArtifactVersion detectedMavenVersion = rti.getApplicationVersion();
    VersionRange vr;// w ww .  ja  v a 2 s  . com
    try {
        vr = VersionRange.createFromVersionSpec("[2.0.8,)");
        if (!containsVersion(vr, detectedMavenVersion)) {
            getLog().warn(
                    "The tree mojo requires at least Maven 2.0.8 to function properly. You may get erroneous results on earlier versions");
        }
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    }

    ArtifactFilter artifactFilter = createResolvingArtifactFilter();

    try {
        // TODO: note that filter does not get applied due to MNG-3236

        rootNode = dependencyTreeBuilder.buildDependencyTree(project, localRepository, artifactFactory,
                artifactMetadataSource, artifactFilter, artifactCollector);

        String dependencyTreeString = serializeDependencyTree(rootNode);

        DependencyUtil.log(dependencyTreeString, getLog());

        postprocessResult();

    } catch (DependencyTreeBuilderException exception) {
        throw new MojoExecutionException("Cannot build project dependency tree", exception);
    } catch (IOException exception) {
        throw new MojoExecutionException("Cannot serialise project dependency tree", exception);
    }

}

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

License:Open Source License

private void parseEntry(Parser.State s, Mapping distroMapping) throws XMLParserException {
    String artifactSpec;//from   w  w w  .  j a  va 2s .c o m
    String dependencyLine;
    VersionRange versionRange = null;

    s.nextMatch("artifactSpec");
    dependencyLine = getArtifactId(artifactSpec = s.nextElement());

    s.nextElement();
    if (s.peek("versionSpec")) {
        try {
            versionRange = VersionRange.createFromVersionSpec(s.nextElement());
        } catch (InvalidVersionSpecificationException e) {
            throw new IllegalStateException("package map contains invalid version spec.", e);
        }
        s.nextElement();
    }

    if (s.peek("ignore")) {
        distroMapping.putEntry(Entry.createIgnoreEntry(artifactSpec, versionRange));
        s.nextElement();
        return;
    } else if (s.peek("bundle")) {
        distroMapping.putEntry(Entry.createBundleEntry(artifactSpec, versionRange));
        s.nextElement();
        return;
    } else if (s.peek("dependencyLine")) {
        dependencyLine = s.nextElement();
        s.nextElement();
    }

    boolean isBootClaspath = false;
    if (s.peek("boot")) {
        isBootClaspath = true;
        s.nextElement();
    }

    HashSet<String> jarFileNames = new HashSet<String>();
    if (s.peek("jars")) {
        try {
            parseJars(s, jarFileNames);
        } catch (Exception e) {
            throw new XMLParserException("Error while parsing jars", e);
        }
    }

    distroMapping.putEntry(new Entry(artifactSpec, versionRange, dependencyLine, jarFileNames, isBootClaspath));
}

From source file:fr.synchrotron.soleil.ica.ci.maven.plugins.soleildependency.mojo.TreeMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    if (mongoDBInstances == null) {
        if (mongoDBHost != null && mongoDBPort != 0) {
            mongoDBInstances = (ArrayList) Arrays
                    .asList(new MongoDBInstance[] { new MongoDBInstance(mongoDBHost, mongoDBPort) });
        }//ww  w  .  j  ava  2  s  . c o  m
        mongoDBInstances = (ArrayList) Arrays
                .asList(new MongoDBInstance[] { new MongoDBInstance("localhost", 27017) });
    }

    if (mongDBName == null) {
        mongDBName = "repo";
    }
    MetadataRetrieverService metadataRetrieverService = new MetadataRetrieverService(
            new MongoDBMetadataRepository(new BasicMongoDBDataSource(mongoDBInstances, mongDBName)));

    ArtifactVersion detectedMavenVersion = rti.getApplicationVersion();
    VersionRange vr;
    try {
        vr = VersionRange.createFromVersionSpec("[2.0.8,)");
        if (!containsVersion(vr, detectedMavenVersion)) {
            getLog().warn(
                    "The tree mojo requires at least Maven 2.0.8 to function properly. You may get eroneous results on earlier versions");
        }
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException(e.getLocalizedMessage());
    }

    if (output != null) {
        getLog().warn("The parameter output is deprecated. Use outputFile instead.");
        this.outputFile = output;
    }

    ArtifactFilter artifactFilter = createResolvingArtifactFilter();

    try {
        rootNode = dependencyTreeBuilder.buildDependencyTree(project, localRepository, artifactFactory,
                artifactMetadataSource, artifactFilter, artifactCollector);

        FileWriter fileWriter = new FileWriter(new File("export-dependency.csv"));
        fileWriter.append(CustomArtifact.toCsvHeaders());

        String dependencyTreeString = serialiseDependencyTree(
                addAndModifyPubDateDependencyTreeWithLog(metadataRetrieverService, fileWriter, rootNode));

        if (outputFile != null) {
            DependencyUtil.write(dependencyTreeString, outputFile, getLog());

            getLog().info("Wrote dependency tree to: " + outputFile);
        } else {
            DependencyUtil.log(dependencyTreeString, getLog());
        }
    } catch (DependencyTreeBuilderException exception) {
        throw new MojoExecutionException("Cannot build project dependency tree", exception);
    } catch (IOException exception) {
        throw new MojoExecutionException("Cannot serialise project dependency tree", exception);
    }
}

From source file:hudson.maven.ModuleDependency.java

License:Open Source License

public VersionRange getVersionAsRange() throws InvalidVersionSpecificationException {
    if (range == null)
        range = VersionRange.createFromVersionSpec(version);
    return range;
}