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

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

Introduction

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

Prototype

public boolean containsVersion(ArtifactVersion version) 

Source Link

Usage

From source file:org.eclipse.m2e.editor.xml.internal.lifecycle.WorkspaceLifecycleMappingProposal.java

License:Open Source License

private static void performIgnore(IMarker mark, LifecycleMappingMetadataSource source)
        throws IOException, CoreException {
    String pluginGroupId = mark.getAttribute(IMavenConstants.MARKER_ATTR_GROUP_ID, ""); //$NON-NLS-1$
    String pluginArtifactId = mark.getAttribute(IMavenConstants.MARKER_ATTR_ARTIFACT_ID, ""); //$NON-NLS-1$
    String pluginVersion = mark.getAttribute(IMavenConstants.MARKER_ATTR_VERSION, ""); //$NON-NLS-1$
    String goal = mark.getAttribute(IMavenConstants.MARKER_ATTR_GOAL, ""); //$NON-NLS-1$
    String id = pluginGroupId + ":" + pluginArtifactId;
    MojoExecutionKey key = new MojoExecutionKey(pluginGroupId, pluginArtifactId, pluginVersion, goal, null,
            null);/*  w w  w . jav  a  2s . co m*/
    boolean found = false;
    for (PluginExecutionMetadata pem : source.getPluginExecutions()) {
        PluginExecutionFilter filter = pem.getFilter();
        if (PluginExecutionAction.ignore.equals(pem.getAction())) {
            if (filter.getGroupId().equals(pluginGroupId) && filter.getArtifactId().equals(pluginArtifactId)) {
                found = true;
                try {
                    VersionRange range = VersionRange.createFromVersionSpec(filter.getVersionRange());
                    DefaultArtifactVersion version = new DefaultArtifactVersion(pluginVersion);
                    if (!range.containsVersion(version)) {
                        filter.setVersionRange("[" + pluginVersion + ",)");
                    }
                } catch (InvalidVersionSpecificationException e) {
                    log.error(e.getMessage(), e);
                }
                if (!filter.getGoals().contains(goal)) {
                    filter.addGoal(goal);
                }
                break;
            }
        }
    }
    if (!found) {
        PluginExecutionMetadata pe = new PluginExecutionMetadata();
        PluginExecutionFilter fil = new PluginExecutionFilter(pluginGroupId, pluginArtifactId,
                "[" + pluginVersion + ",)", goal);
        pe.setFilter(fil);
        source.addPluginExecution(pe);
        Xpp3Dom actionDom = new Xpp3Dom("action");
        actionDom.addChild(new Xpp3Dom(PluginExecutionAction.ignore.name()));
        pe.setActionDom(actionDom);
    }

}

From source file:org.eclipse.tycho.nexus.internal.plugin.cache.ParsedRequest.java

License:Open Source License

@SuppressWarnings("deprecation")
String selectVersion(final Versioning versioning, final VersionRange versionRange, final boolean findSnapshots)
        throws ItemNotFoundException {
    // do not rely on LATEST and RELEASE tag, because they not necessarily correspond to highest version number
    String selectedVersion = getLatestVersion(versioning, findSnapshots);

    if (versionRange != null && !versionRange.containsVersion(new DefaultArtifactVersion(selectedVersion))) {
        final List<ArtifactVersion> versions = new ArrayList<ArtifactVersion>();
        for (final String artifactVersion : versioning.getVersions()) {
            if (findSnapshots || !artifactVersion.endsWith("-SNAPSHOT")) {
                versions.add(new DefaultArtifactVersion(artifactVersion));
            }/*from w w  w.  j a  v a 2 s  .  co m*/
        }
        final ArtifactVersion matchedVersion = versionRange.matchVersion(versions);
        if (matchedVersion != null) {
            selectedVersion = matchedVersion.toString();
        } else {
            throw new ItemNotFoundException("No version found within range");
        }
    }
    return selectedVersion;
}

From source file:org.freehep.maven.nar.NarIntegrationTestMojo.java

License:Open Source License

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

    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");
    }//from w  w  w  .  jav a 2s .  c o m

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

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

        junitArtifact = (Artifact) projectArtifactMap.get("junit:junit");

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

        if (testNgArtifact != null) {
            addArtifact(surefireBooter, testNgArtifact);

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

            // 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) {
        if (testNgArtifact == null) {
            throw new MojoExecutionException("suiteXmlFiles is configured, but there is no TestNG dependency");
        }
        for (int i = 0; i < suiteXmlFiles.length; i++) {
            File file = suiteXmlFiles[i];
            if (file.exists()) {
                surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGXmlTestSuite",
                        new Object[] { file, testSourceDirectory.getAbsolutePath() });
            }
        }
    } 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();

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

            for (int i = 0; i < testRegexes.length; i++) {
                includes.add("**/" + testRegexes[i] + ".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[] { "**/Abstract*Test.java", "**/Abstract*TestCase.java", "**/*$*" }));
            }
        }

        if (testNgArtifact != null) {
            surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGDirectoryTestSuite",
                    new Object[] { testClassesDirectory, includes, excludes, groups, excludedGroups,
                            Boolean.valueOf(parallel), new Integer(threadCount),
                            testSourceDirectory.getAbsolutePath() });
        } else {
            String junitDirectoryTestSuite;
            // FREEHEP NP check
            if (junitArtifact != 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 :");

    // no need to add classes/test classes directory here - they are in the
    // classpath elements already

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

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

        surefireBooter.addClassPathUrl(classpathElement);
    }

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

    ForkConfiguration fork = new ForkConfiguration();

    // FREEHEP
    if (project.getPackaging().equals("nar") || (getNarManager().getNarDependencies("test").size() > 0))
        forkMode = "pertest";

    fork.setForkMode(forkMode);

    processSystemProperties(!fork.isForking());

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

    if (fork.isForking()) {
        fork.setSystemProperties(systemProperties);

        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);
        }

        // BEGINFREEHEP
        if (argLine == null)
            argLine = "";

        StringBuffer javaLibraryPath = new StringBuffer();
        if (testJNIModule()) {
            // Add libraries to java.library.path for testing
            File jniLibraryPathEntry = new File(project.getBasedir(), "target/nar/lib/" + getAOL() + "/jni");
            if (jniLibraryPathEntry.exists()) {
                getLog().debug("Adding library directory to java.library.path: " + jniLibraryPathEntry);
                if (javaLibraryPath.length() > 0)
                    javaLibraryPath.append(File.pathSeparator);
                javaLibraryPath.append(jniLibraryPathEntry);
            }

            File sharedLibraryPathEntry = new File(project.getBasedir(),
                    "target/nar/lib/" + getAOL() + "/shared");
            if (sharedLibraryPathEntry.exists()) {
                getLog().debug("Adding library directory to java.library.path: " + sharedLibraryPathEntry);
                if (javaLibraryPath.length() > 0)
                    javaLibraryPath.append(File.pathSeparator);
                javaLibraryPath.append(sharedLibraryPathEntry);
            }

            // add jar file to classpath, as one may want to read a
            // properties file for artifactId and version
            String jarFile = "target/" + project.getArtifactId() + "-" + project.getVersion() + ".jar";
            getLog().debug("Adding to surefire test classpath: " + jarFile);
            surefireBooter.addClassPathUrl(jarFile);
        }

        List dependencies = getNarManager().getNarDependencies("test");
        for (Iterator i = dependencies.iterator(); i.hasNext();) {
            NarArtifact dependency = (NarArtifact) i.next();
            // FIXME this should be overridable
            // NarInfo info = dependency.getNarInfo();
            // String binding = info.getBinding(getAOL(), Library.STATIC);
            // NOTE: fixed to shared, jni
            String[] bindings = { Library.SHARED, Library.JNI };
            for (int j = 0; j < bindings.length; j++) {
                String binding = bindings[j];
                if (!binding.equals(Library.STATIC)) {
                    File depLibPathEntry = new File(getNarManager().getNarFile(dependency).getParent(),
                            "nar/lib/" + getAOL() + "/" + binding);
                    if (depLibPathEntry.exists()) {
                        getLog().debug("Adding dependency directory to java.library.path: " + depLibPathEntry);
                        if (javaLibraryPath.length() > 0)
                            javaLibraryPath.append(File.pathSeparator);
                        javaLibraryPath.append(depLibPathEntry);
                    }
                }
            }
        }

        // add final javalibrary path
        if (javaLibraryPath.length() > 0) {
            // NOTE java.library.path only works for the jni lib itself, and
            // not for its dependent shareables.
            // NOTE: java.library.path does not work with arguments with
            // spaces as
            // SureFireBooter splits the line in parts and then quotes
            // it wrongly
            NarUtil.addLibraryPathToEnv(javaLibraryPath.toString(), environmentVariables, getOS());
        }

        // necessary to find WinSxS
        if (getOS().equals(OS.WINDOWS)) {
            environmentVariables.put("SystemRoot", NarUtil.getEnv("SystemRoot", "SystemRoot", "C:\\Windows"));
        }
        // ENDFREEHEP

        fork.setArgLine(argLine);

        fork.setEnvironmentVariables(environmentVariables);

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

            fork.setDebug(true);
        }
    }

    surefireBooter.setRedirectTestOutputToFile(redirectTestOutputToFile);

    surefireBooter.setForkConfiguration(fork);

    surefireBooter.setChildDelegation(childDelegation);

    surefireBooter.setReportsDirectory(reportsDirectory);

    surefireBooter.setUseSystemClassLoader(useSystemClassLoader);

    addReporters(surefireBooter, fork.isForking());

    return surefireBooter;
}

From source file:org.jboss.tools.maven.core.internal.resolution.ArtifactResolutionService.java

License:Open Source License

List<String> getAvailableReleasedVersions(Artifact artifact, List<ArtifactRepository> repositories,
        IProgressMonitor monitor) throws CoreException {

    ArtifactMetadataSource source = getArtifactMetadataSource();

    IMaven maven = MavenPlugin.getMaven();
    ArtifactRepository localRepository = maven.getLocalRepository();
    try {/*from  w w  w . java2 s . co  m*/
        String versionRangeSpec = artifact.getVersion() == null ? "[0,)" : artifact.getVersion(); //$NON-NLS-1$
        VersionRange versionRange = VersionRange.createFromVersionSpec(versionRangeSpec);
        artifact.setVersionRange(versionRange);
        List<ArtifactVersion> fullVersions = source.retrieveAvailableVersions(artifact, localRepository,
                repositories);
        List<String> versions = new ArrayList<String>(fullVersions.size());
        for (ArtifactVersion aVersion : fullVersions) {
            String version = aVersion.toString();
            if (version.endsWith("-SNAPSHOT")) { //$NON-NLS-1$
                continue;
            }
            if (versionRange.containsVersion(aVersion)) {
                versions.add(version);
            }
        }
        return versions;
    } catch (Exception e) {
        throw toCoreException(e);
    }
}

From source file:org.kaazing.bower.dependency.maven.plugin.UnpackBowerDependencyMojo.java

License:Open Source License

/**
 * Finds matching tag for a requiredVersion
 * @param requiredVersion (Can be semver version or version range)
 * @param tagList//ww  w.j av  a 2s .  c om
 * @return
 * @throws MojoExecutionException
 */
String findMatchingTag(String requiredVersion, List<Ref> tagList) throws MojoExecutionException {
    String tagPrefix = "refs/tags/";
    List<ArtifactVersion> availableVersions = new ArrayList<>();
    for (Ref tag : tagList) {
        String tagVersion = tag.getName().toString().replace(tagPrefix, "");
        log.debug("Found tag version \"" + tagVersion + "\" from tag with name \"" + tag.getName() + "\"");
        try {
            // Check that it follows SEMVER
            Version.valueOf(tagVersion);
            // If it does add it to available versions
            availableVersions.add(new DefaultArtifactVersion(tagVersion));
        } catch (UnexpectedCharacterException e) {
            log.warn("Found tag version \"" + tagVersion + "\" from tag with name \"" + tag.getName()
                    + "\" that does not match semver spec");
        }
    }
    Collections.sort(availableVersions);

    Matcher matcher = SEMVER_SIMPLE_VERSION_MATCHER.matcher(requiredVersion);
    boolean isRange = !matcher.matches();

    String tag = null;

    if (isRange) {
        log.info("version is a range");
        VersionRange versionRange;
        try {
            versionRange = VersionRange.createFromVersionSpec(requiredVersion);
        } catch (InvalidVersionSpecificationException e) {
            throw new MojoExecutionException("Unable to parse version range " + requiredVersion, e);
        }
        for (ArtifactVersion availableVersion : availableVersions) {
            if (versionRange.containsVersion(availableVersion)) {
                tag = availableVersion.toString();
            }
        }
    } else {
        log.info("version is not a range");
        for (ArtifactVersion availableVersion : availableVersions) {
            log.info(availableVersion.toString() + " compared to " + requiredVersion.toString());
            if (requiredVersion.equals(availableVersion.toString())) {
                log.info("found tag! " + availableVersion.toString());
                tag = availableVersion.toString();
            }
        }
    }

    if (tag == null) {
        StringBuilder messageBuilder = new StringBuilder("Could not find a version to match: ");
        messageBuilder.append(requiredVersion);
        messageBuilder.append(", available versions are:");
        for (ArtifactVersion availableVersion : availableVersions) {
            messageBuilder.append("\t");
            messageBuilder.append(availableVersion);
            messageBuilder.append(",");
        }
        throw new MojoExecutionException(messageBuilder.toString());
    }
    tag = "tags/" + tag;
    return tag;
}

From source file:org.kuali.maven.plugins.graph.filter.PatternsFilter.java

License:Educational Community License

protected boolean isVersionIncludedInRange(String version, String range) {
    try {/*from w  ww.ja  va2  s  .  c  o  m*/
        VersionRange versionRange = VersionRange.createFromVersionSpec(range);
        ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
        return versionRange.containsVersion(artifactVersion);
    } catch (InvalidVersionSpecificationException e) {
        throw new FilterException(e);
    }
}

From source file:org.ops4j.pax.construct.util.PomUtils.java

License:Apache License

/**
 * @param range compatible range/*  w w  w . j  av  a 2s.  com*/
 * @param version candidate version
 * @return true if this version is compatible, otherwise false
 */
private static boolean isCompatible(VersionRange range, ArtifactVersion version) {
    if (version.getMajorVersion() > 10000000 || ArtifactUtils.isSnapshot(version.toString())) {
        return false; // ignore snapshots and possible timestamped releases
    } else if (range != null && !range.containsVersion(version)) {
        return false; // ignore this version as it's not compatible
    }

    return true;
}