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:org.apache.tomcat.maven.plugin.tomcat6.AbstractRunMojo.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.
 *
 * @param additionalWebapp 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.
 *//*  w  w  w  .  j a v a 2  s .c  o m*/
protected Artifact getArtifact(AbstractWebapp additionalWebapp) throws MojoExecutionException {

    Artifact artifact;
    VersionRange vr;
    try {
        vr = VersionRange.createFromVersionSpec(additionalWebapp.getVersion());
    } catch (InvalidVersionSpecificationException e) {
        getLog().warn("fail to create versionRange from version: " + additionalWebapp.getVersion(), e);
        vr = VersionRange.createFromVersion(additionalWebapp.getVersion());
    }

    if (StringUtils.isEmpty(additionalWebapp.getClassifier())) {
        artifact = artifactFactory.createDependencyArtifact(additionalWebapp.getGroupId(),
                additionalWebapp.getArtifactId(), vr, additionalWebapp.getType(), null, Artifact.SCOPE_COMPILE);
    } else {
        artifact = artifactFactory.createDependencyArtifact(additionalWebapp.getGroupId(),
                additionalWebapp.getArtifactId(), vr, additionalWebapp.getType(),
                additionalWebapp.getClassifier(), Artifact.SCOPE_COMPILE);
    }

    try {
        artifactResolver.resolve(artifact, project.getRemoteArtifactRepositories(), this.artifactRepository);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve artifact.", e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Unable to find artifact.", e);
    }

    return artifact;
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.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.
 *
 * @param additionalWebapp 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.
 *//*from  w  w  w  . j  av  a 2  s. c  o m*/
protected Artifact getArtifact(AbstractWebapp additionalWebapp) throws MojoExecutionException {

    Artifact artifact;
    VersionRange vr;
    try {
        vr = VersionRange.createFromVersionSpec(additionalWebapp.getVersion());
    } catch (InvalidVersionSpecificationException e) {
        getLog().warn("fail to create versionRange from version: " + additionalWebapp.getVersion(), e);
        vr = VersionRange.createFromVersion(additionalWebapp.getVersion());
    }

    if (StringUtils.isEmpty(additionalWebapp.getClassifier())) {
        artifact = factory.createDependencyArtifact(additionalWebapp.getGroupId(),
                additionalWebapp.getArtifactId(), vr, additionalWebapp.getType(), null, Artifact.SCOPE_COMPILE);
    } else {
        artifact = factory.createDependencyArtifact(additionalWebapp.getGroupId(),
                additionalWebapp.getArtifactId(), vr, additionalWebapp.getType(),
                additionalWebapp.getClassifier(), Artifact.SCOPE_COMPILE);
    }

    try {
        resolver.resolve(artifact, project.getRemoteArtifactRepositories(), this.local);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve artifact.", e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Unable to find artifact.", e);
    }

    return artifact;
}

From source file:org.apache.tuscany.maven.plugin.eclipse.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Returns the list of project artifacts. Also artifacts generated from referenced projects will be added, but with
 * the <code>resolved</code> property set to true.
 *
 * @return list of projects artifacts/*ww w  .j  a va  2s .com*/
 * @throws MojoExecutionException if unable to parse dependency versions
 */
private Set getProjectArtifacts() throws MojoExecutionException {
    // keep it sorted, this should avoid random classpath order in tests
    Set artifacts = new TreeSet();

    for (Iterator dependencies = getProject().getDependencies().iterator(); dependencies.hasNext();) {
        Dependency dependency = (Dependency) dependencies.next();

        String groupId = dependency.getGroupId();
        String artifactId = dependency.getArtifactId();
        VersionRange versionRange;
        try {
            versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
        } catch (InvalidVersionSpecificationException e) {
            throw new MojoExecutionException(Messages.getString("AbstractIdeSupportMojo.unabletoparseversion", //$NON-NLS-1$
                    new Object[] { dependency.getArtifactId(), dependency.getVersion(), dependency.getManagementKey(),
                            e.getMessage() }),
                    e);
        }

        String type = dependency.getType();
        if (type == null) {
            type = Constants.PROJECT_PACKAGING_JAR;
        }
        String classifier = dependency.getClassifier();
        boolean optional = dependency.isOptional();
        String scope = dependency.getScope();
        if (scope == null) {
            scope = Artifact.SCOPE_COMPILE;
        }

        Artifact art = getArtifactFactory().createDependencyArtifact(groupId, artifactId, versionRange, type,
                classifier, scope, optional);

        if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
            art.setFile(new File(dependency.getSystemPath()));
        }

        List exclusions = new ArrayList();
        for (Iterator j = dependency.getExclusions().iterator(); j.hasNext();) {
            Exclusion e = (Exclusion) j.next();
            exclusions.add(e.getGroupId() + ":" + e.getArtifactId()); //$NON-NLS-1$
        }

        ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);

        art.setDependencyFilter(newFilter);

        artifacts.add(art);
    }

    return artifacts;
}

From source file:org.apache.tuscany.maven.plugin.eclipse.AbstractIdeSupportMojo.java

License:Apache License

private Map createManagedVersionMap(ArtifactFactory artifactFactory, String projectId,
        DependencyManagement dependencyManagement) throws MojoExecutionException {
    Map map;/*  www .  j a va2  s.  c  o m*/
    if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
        map = new HashMap();
        for (Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext();) {
            Dependency d = (Dependency) i.next();

            try {
                VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
                Artifact artifact = artifactFactory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(),
                        versionRange, d.getType(), d.getClassifier(), d.getScope(), d.isOptional());
                map.put(d.getManagementKey(), artifact);
            } catch (InvalidVersionSpecificationException e) {
                throw new MojoExecutionException(
                        Messages.getString("AbstractIdeSupportMojo.unabletoparseversion", new Object[] { //$NON-NLS-1$
                                projectId, d.getVersion(), d.getManagementKey(), e.getMessage() }),
                        e);
            }
        }
    } else {
        map = Collections.EMPTY_MAP;
    }
    return map;
}

From source file:org.apache.tuscany.maven.plugin.surefire.OSGiSurefirePlugin.java

License:Apache License

private OSGiSurefireBooter constructSurefireBooter() throws MojoExecutionException, MojoFailureException {
    OSGiSurefireBooter surefireBooter = new OSGiSurefireBooter();

    // Build up the surefire boot classpath
    // * org.apache.tuscany.sca:tuscany-maven-surefire-osgi-plugin (non-transitive 
    //   to exclude maven dependencies 
    // * org.apache.tuscany.sca:tuscany-node-launcher-equinox (transitive)
    // * org.apache.maven.surefire:surefire-booter (transitive)
    // Get the artifact for the OSGi surefire plugin
    Artifact osgiArtifact = artifactFactory.createArtifact(pluginGroupId, pluginArtifactId, pluginVersion,
            Artifact.SCOPE_TEST, "maven-plugin");
    try {/*from  ww  w .  ja v a 2 s  . c  o  m*/
        artifactResolver.resolve(osgiArtifact, remoteRepositories, localRepository);
        surefireBooter.addSurefireBootClassPathUrl(osgiArtifact.getFile().getAbsolutePath());
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to resolve " + osgiArtifact);
    }

    Artifact launcher = (Artifact) pluginArtifactMap
            .get("org.apache.tuscany.sca:tuscany-node-launcher-equinox");

    // Look up the surefire-booter
    Artifact surefireArtifact = (Artifact) pluginArtifactMap.get("org.apache.maven.surefire:surefire-booter");
    if (surefireArtifact == null) {
        throw new MojoExecutionException("Unable to locate surefire-booter in the list of plugin artifacts");
    }

    surefireArtifact.isSnapshot(); // TODO: this is ridiculous, but it fixes getBaseVersion to be -SNAPSHOT if
    // needed

    Artifact junitArtifact;
    Artifact testNgArtifact;
    try {
        addArtifact(surefireBooter, surefireArtifact);
        addArtifact(surefireBooter, launcher);

        junitArtifact = (Artifact) projectArtifactMap.get(junitArtifactName);
        // SUREFIRE-378, junit can have an alternate artifact name
        if (junitArtifact == null && "junit:junit".equals(junitArtifactName)) {
            junitArtifact = (Artifact) projectArtifactMap.get("junit:junit-dep");
        }

        // TODO: this is pretty manual, but I'd rather not require the plugin > dependencies section right now
        testNgArtifact = (Artifact) projectArtifactMap.get(testNGArtifactName);

        if (testNgArtifact != null) {
            VersionRange range = VersionRange.createFromVersionSpec("[4.7,)");
            if (!range.containsVersion(new DefaultArtifactVersion(testNgArtifact.getVersion()))) {
                throw new MojoFailureException(
                        "TestNG support requires version 4.7 or above. You have declared version "
                                + testNgArtifact.getVersion());
            }

            convertTestNGParameters();

            if (this.testClassesDirectory != null) {
                properties.setProperty("testng.test.classpath", testClassesDirectory.getAbsolutePath());
            }

            addArtifact(surefireBooter, testNgArtifact);

            // The plugin uses a JDK based profile to select the right testng. We might be explicity using a
            // different one since its based on the source level, not the JVM. Prune using the filter.
            addProvider(surefireBooter, "surefire-testng", surefireArtifact.getBaseVersion(), testNgArtifact);
        } else if (junitArtifact != null && junitArtifact.getBaseVersion().startsWith("4")) {
            addProvider(surefireBooter, "surefire-junit4", surefireArtifact.getBaseVersion(), null);
        } else {
            // add the JUnit provider as default - it doesn't require JUnit to be present,
            // since it supports POJO tests.
            addProvider(surefireBooter, "surefire-junit", surefireArtifact.getBaseVersion(), null);
        }
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException(
                "Unable to locate required surefire provider dependency: " + e.getMessage(), e);
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("Error determining the TestNG version requested: " + e.getMessage(),
                e);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Error to resolving surefire provider dependency: " + e.getMessage(),
                e);
    }

    if (suiteXmlFiles != null && suiteXmlFiles.length > 0 && test == null) {
        if (testNgArtifact == null) {
            throw new MojoExecutionException("suiteXmlFiles is configured, but there is no TestNG dependency");
        }

        // TODO: properties should be passed in here too
        surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGXmlTestSuite",
                new Object[] { suiteXmlFiles, testSourceDirectory.getAbsolutePath(),
                        testNgArtifact.getVersion(), testNgArtifact.getClassifier(), properties,
                        reportsDirectory });
    } else {
        List includes;
        List excludes;

        if (test != null) {
            // Check to see if we are running a single test. The raw parameter will
            // come through if it has not been set.

            // FooTest -> **/FooTest.java

            includes = new ArrayList();

            excludes = new ArrayList();

            if (failIfNoTests == null) {
                failIfNoTests = Boolean.TRUE;
            }

            String[] testRegexes = StringUtils.split(test, ",");

            for (int i = 0; i < testRegexes.length; i++) {
                String testRegex = testRegexes[i];
                if (testRegex.endsWith(".java")) {
                    testRegex = testRegex.substring(0, testRegex.length() - 5);
                }
                // Allow paths delimited by '.' or '/'
                testRegex = testRegex.replace('.', '/');
                includes.add("**/" + testRegex + ".java");
            }
        } else {
            includes = this.includes;

            excludes = this.excludes;

            // defaults here, qdox doesn't like the end javadoc value
            // Have to wrap in an ArrayList as surefire expects an ArrayList instead of a List for some reason
            if (includes == null || includes.size() == 0) {
                includes = new ArrayList(
                        Arrays.asList(new String[] { "**/Test*.java", "**/*Test.java", "**/*TestCase.java" }));
            }
            if (excludes == null || excludes.size() == 0) {
                excludes = new ArrayList(Arrays.asList(new String[] { "**/*$*" }));
            }
        }

        if (testNgArtifact != null) {
            surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGDirectoryTestSuite",
                    new Object[] { testClassesDirectory, includes, excludes,
                            testSourceDirectory.getAbsolutePath(), testNgArtifact.getVersion(),
                            testNgArtifact.getClassifier(), properties, reportsDirectory });
        } else {
            String junitDirectoryTestSuite;
            if (junitArtifact != null && junitArtifact.getBaseVersion() != null
                    && junitArtifact.getBaseVersion().startsWith("4")) {
                junitDirectoryTestSuite = "org.apache.maven.surefire.junit4.JUnit4DirectoryTestSuite";
            } else {
                junitDirectoryTestSuite = "org.apache.maven.surefire.junit.JUnitDirectoryTestSuite";
            }

            // fall back to JUnit, which also contains POJO support. Also it can run
            // classes compiled against JUnit since it has a dependency on JUnit itself.
            surefireBooter.addTestSuite(junitDirectoryTestSuite,
                    new Object[] { testClassesDirectory, includes, excludes });
        }
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    getLog().debug("Test Classpath :");

    classpathElements.remove(classesDirectory.getAbsolutePath());
    classpathElements.remove(testClassesDirectory.getAbsolutePath());
    /*
    // Check if we need to add configured classes/test classes directories here.
    // If they are configured, we should remove the default to avoid conflicts.
    if (!project.getBuild().getOutputDirectory().equals(classesDirectory.getAbsolutePath())) {
    classpathElements.remove(project.getBuild().getOutputDirectory());
    classpathElements.add(classesDirectory.getAbsolutePath());
    }
    if (!project.getBuild().getTestOutputDirectory().equals(testClassesDirectory.getAbsolutePath())) {
    classpathElements.remove(project.getBuild().getTestOutputDirectory());
    classpathElements.add(testClassesDirectory.getAbsolutePath());
    }
    */

    for (Iterator i = classpathElements.iterator(); i.hasNext();) {
        String classpathElement = (String) i.next();

        getLog().debug("  " + classpathElement);

        surefireBooter.addClassPathUrl(classpathElement);
    }

    Toolchain tc = getToolchain();

    if (tc != null) {
        getLog().info("Toolchain in surefire-plugin: " + tc);
        if (ForkConfiguration.FORK_NEVER.equals(forkMode)) {
            forkMode = ForkConfiguration.FORK_ONCE;
        }
        if (jvm != null) {
            getLog().warn("Toolchains are ignored, 'executable' parameter is set to " + jvm);
        } else {
            jvm = tc.findTool("java"); //NOI18N
        }
    }

    if (additionalClasspathElements != null) {
        for (Iterator i = additionalClasspathElements.iterator(); i.hasNext();) {
            String classpathElement = (String) i.next();

            getLog().debug("  " + classpathElement);

            surefireBooter.addClassPathUrl(classpathElement);
        }
    }

    // ----------------------------------------------------------------------
    // Forking
    // ----------------------------------------------------------------------

    ForkConfiguration fork = new ForkConfiguration();

    fork.setForkMode(forkMode);

    processSystemProperties(!fork.isForking());

    if (getLog().isDebugEnabled()) {
        showMap(systemProperties, "system property");
    }

    if (fork.isForking()) {
        useSystemClassLoader = useSystemClassLoader == null ? Boolean.TRUE : useSystemClassLoader;
        fork.setUseSystemClassLoader(useSystemClassLoader.booleanValue());
        fork.setUseManifestOnlyJar(useManifestOnlyJar);

        fork.setSystemProperties(systemProperties);

        if ("true".equals(debugForkedProcess)) {
            debugForkedProcess = "-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005";
        }

        fork.setDebugLine(debugForkedProcess);

        if (jvm == null || "".equals(jvm)) {
            // use the same JVM as the one used to run Maven (the "java.home" one)
            jvm = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
            getLog().debug("Using JVM: " + jvm);
        }

        fork.setJvmExecutable(jvm);

        if (workingDirectory != null) {
            fork.setWorkingDirectory(workingDirectory);
        } else {
            fork.setWorkingDirectory(basedir);
        }

        fork.setArgLine(argLine);

        fork.setEnvironmentVariables(environmentVariables);

        if (getLog().isDebugEnabled()) {
            showMap(environmentVariables, "environment variable");

            fork.setDebug(true);
        }

        if (argLine != null) {
            List args = Arrays.asList(argLine.split(" "));
            if (args.contains("-da") || args.contains("-disableassertions")) {
                enableAssertions = false;
            }
        }
    }

    surefireBooter.setFailIfNoTests(failIfNoTests == null ? false : failIfNoTests.booleanValue());

    surefireBooter.setForkedProcessTimeoutInSeconds(forkedProcessTimeoutInSeconds);

    surefireBooter.setRedirectTestOutputToFile(redirectTestOutputToFile);

    surefireBooter.setForkConfiguration(fork);

    surefireBooter.setChildDelegation(childDelegation);

    surefireBooter.setEnableAssertions(enableAssertions);

    surefireBooter.setReportsDirectory(reportsDirectory);

    addReporters(surefireBooter, fork.isForking());

    return surefireBooter;
}

From source file:org.apache.tuscany.maven.plugin.surefire.OSGiSurefirePlugin.java

License:Apache License

protected Artifact getArtifact(String groupId, String artifactId) throws MojoExecutionException {
    Artifact artifact;/*from ww w .  j  a  v  a  2s.  co m*/
    VersionRange vr;
    try {
        vr = VersionRange.createFromVersionSpec(project.getVersion());
    } catch (InvalidVersionSpecificationException e1) {
        vr = VersionRange.createFromVersion(project.getVersion());
    }
    artifact = artifactFactory.createDependencyArtifact(groupId, artifactId, vr, "jar", null,
            Artifact.SCOPE_TEST);

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

    return artifact;
}

From source file:org.automagic.deps.doctor.spy.PomSpyImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private boolean isLowerThanCurrent(TransitiveDependency newDependency, Optional<Node> currentVersionNode)
        throws InvalidVersionSpecificationException, OverConstrainedVersionException {
    String version = currentVersionNode.get().getTextContent().trim();
    Optional<String> propertyName = getVersionPropertyName(version);
    if (propertyName.isPresent()) {
        Optional<Node> propertyNode = Utils.getNode("/project/properties/" + propertyName.get(), document);
        if (!propertyNode.isPresent()) {
            return false;
        }/*from   w  w w.j av a 2 s  . c om*/
        version = propertyNode.get().getTextContent().trim();
    }
    VersionRange versionRange = VersionRange.createFromVersionSpec(version);
    ArtifactVersion currentVersion = versionRange.getSelectedVersion(newDependency.getArtifact());
    int result = newDependency.getVersion().compareTo(currentVersion);
    return result < 0;
}

From source file:org.axway.grapes.maven.resolver.ArtifactResolver.java

/**
 * Resolve a dependency artifact/*from   w w w.  ja  v a2 s .  c om*/
 *
 * @param project MavenProject
 * @param dependency dependency
 * @return Artifact
 */
public Artifact resolveArtifact(final MavenProject project, final Dependency dependency)
        throws MojoExecutionException {
    // Manage version ranges
    String version = dependency.getVersion();
    try {
        if (!version.matches("[0-9.]*")) {
            final VersionRange range = VersionRange.createFromVersionSpec(version);
            version = getArtifactVersion(range);
        }
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("Failed to handle version range of " + dependency.toString(), e);
    }

    final DefaultArtifactHandler handler = new DefaultArtifactHandler();
    handler.setExtension(dependency.getType());

    final Artifact artifact = new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), version,
            null, dependency.getType(), dependency.getClassifier(), handler);

    resolveArtifact(project, artifact);

    return artifact;
}

From source file:org.basepom.mojo.duplicatefinder.artifact.MavenCoordinates.java

License:Apache License

public MavenCoordinates(final Dependency dependency) throws InvalidVersionSpecificationException {
    checkNotNull(dependency, "dependency is null");

    this.artifactId = checkNotNull(dependency.getArtifactId(), "artifactId for dependency '%s' is null",
            dependency);/*from w  ww. ja  va  2 s .c  o m*/
    this.groupId = checkNotNull(dependency.getGroupId(), "groupId for dependency '%s' is null", dependency);

    final String version = dependency.getVersion();
    this.version = version == null ? Optional.<ArtifactVersion>absent()
            : Optional.of(new DefaultArtifactVersion(version));

    if (this.version.isPresent()) {
        this.versionRange = Optional.of(VersionRange.createFromVersionSpec(version));
    } else {
        this.versionRange = Optional.absent();
    }

    final String type = dependency.getType();
    final String classifier = dependency.getClassifier();
    if ("test-jar".equals(type)) {
        this.classifier = Optional.of(MoreObjects.firstNonNull(classifier, "tests"));
        this.type = "jar";
    } else {
        this.type = MoreObjects.firstNonNull(type, "jar");
        this.classifier = Optional.fromNullable(classifier);
    }
}

From source file:org.bsc.maven.plugin.findclass.DependencyWrapper.java

License:Apache License

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