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:ch.ivyteam.ivy.maven.InstallEngineMojo.java

License:Apache License

private void ensureEngineIsInstalled() throws MojoExecutionException {
    VersionRange ivyVersionRange = getIvyVersionRange();
    if (identifyAndGetEngineDirectory() == null) {
        handleNoInstalledEngine();/*from   w  ww  . j  a v a  2 s  .c om*/
    } else {
        if (engineDirectoryIsEmpty()) {
            getRawEngineDirectory().mkdirs();
        }
        ArtifactVersion installedEngineVersion = getInstalledEngineVersion(getRawEngineDirectory());

        if (installedEngineVersion == null || !ivyVersionRange.containsVersion(installedEngineVersion)) {
            handleWrongIvyVersion(installedEngineVersion);
        }
    }
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Checks whether the currently running Maven satisfies the specified version (range).
 *
 * @param version The version range to test for, must not be <code>null</code>.
 * @return <code>true</code> if the current Maven version matches the specified version range, <code>false</code>
 *         otherwise.//from   w w  w.  j  av  a2  s . c  o  m
 */
protected boolean isMavenVersion(String version) {
    try {
        VersionRange versionRange = VersionRange.createFromVersionSpec(version);
        ArtifactVersion mavenVersion = runtimeInformation.getApplicationVersion();
        return versionRange.containsVersion(mavenVersion);
    } catch (InvalidVersionSpecificationException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

From source file:com.github.klieber.phantomjs.util.VersionUtil.java

License:Open Source License

public static boolean isWithin(String version, VersionRange versionRange) {
    ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
    ArtifactVersion recommendedVersion = versionRange.getRecommendedVersion();
    // treat recommended version as minimum version
    return recommendedVersion != null ? VersionUtil.isLessThanOrEqualTo(recommendedVersion, artifactVersion)
            : versionRange.containsVersion(artifactVersion);
}

From source file:com.github.maven_nar.NarIntegrationTestMojo.java

License:Apache License

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

    final Artifact surefireArtifact = (Artifact) this.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  ww  w.  ja v  a2s.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) this.projectArtifactMap.get(this.junitArtifactName);
        // SUREFIRE-378, junit can have an alternate artifact name
        if (junitArtifact == null && "junit:junit".equals(this.junitArtifactName)) {
            junitArtifact = (Artifact) this.projectArtifactMap.get("junit:junit-dep");
        }

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

        if (testNgArtifact != null) {
            final 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) {
                this.properties.setProperty("testng.test.classpath",
                        this.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 (final ArtifactNotFoundException e) {
        throw new MojoExecutionException(
                "Unable to locate required surefire provider dependency: " + e.getMessage(), e);
    } catch (final InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("Error determining the TestNG version requested: " + e.getMessage(),
                e);
    } catch (final ArtifactResolutionException e) {
        throw new MojoExecutionException("Error to resolving surefire provider dependency: " + e.getMessage(),
                e);
    }

    if (this.suiteXmlFiles != null && this.suiteXmlFiles.length > 0 && this.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[] { this.suiteXmlFiles, this.testSourceDirectory.getAbsolutePath(),
                        testNgArtifact.getBaseVersion(), testNgArtifact.getClassifier(), this.properties,
                        this.reportsDirectory });
    } else {
        List includeList;
        List excludeList;

        if (this.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

            includeList = new ArrayList();

            excludeList = new ArrayList();

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

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

            for (final String testRegexe : testRegexes) {
                String testRegex = testRegexe;
                if (testRegex.endsWith(".java")) {
                    testRegex = testRegex.substring(0, testRegex.length() - 5);
                }
                // Allow paths delimited by '.' or '/'
                testRegex = testRegex.replace('.', '/');
                includeList.add("**/" + testRegex + ".java");
            }
        } else {
            includeList = this.includes;

            excludeList = 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 (includeList == null || includeList.size() == 0) {
                includeList = new ArrayList(
                        Arrays.asList(new String[] { "**/Test*.java", "**/*Test.java", "**/*TestCase.java" }));
            }
            if (excludeList == null || excludeList.size() == 0) {
                excludeList = new ArrayList(Arrays.asList(new String[] { "**/*$*" }));
            }
        }

        if (testNgArtifact != null) {
            surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGDirectoryTestSuite",
                    new Object[] { this.testClassesDirectory, includeList, excludeList,
                            this.testSourceDirectory.getAbsolutePath(), testNgArtifact.getBaseVersion(),
                            testNgArtifact.getClassifier(), this.properties, this.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[] { this.testClassesDirectory, includeList, excludeList });
        }
    }

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

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

    // 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 (!this.project.getBuild().getOutputDirectory().equals(this.classesDirectory.getAbsolutePath())) {
        this.classpathElements.remove(this.project.getBuild().getOutputDirectory());
        this.classpathElements.add(this.classesDirectory.getAbsolutePath());
    }
    if (!this.project.getBuild().getTestOutputDirectory().equals(this.testClassesDirectory.getAbsolutePath())) {
        this.classpathElements.remove(this.project.getBuild().getTestOutputDirectory());
        this.classpathElements.add(this.testClassesDirectory.getAbsolutePath());
    }

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

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

        surefireBooter.addClassPathUrl(classpathElement);
    }

    final Toolchain tc = getToolchain();

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

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

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

            surefireBooter.addClassPathUrl(classpathElement);
        }
    }

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

    final ForkConfiguration fork = new ForkConfiguration();

    // DUNS
    if (this.project.getPackaging().equals("nar") || getNarArtifacts().size() > 0) {
        this.forkMode = "pertest";
    }

    fork.setForkMode(this.forkMode);

    processSystemProperties(!fork.isForking());

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

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

        fork.setSystemProperties(this.systemProperties);

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

        fork.setDebugLine(this.debugForkedProcess);

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

        fork.setJvmExecutable(this.jvm);

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

        // BEGINDUNS
        if (this.argLine == null) {
            this.argLine = "";
        }

        final StringBuffer javaLibraryPath = new StringBuffer();
        if (testJNIModule()) {
            // Add libraries to java.library.path for testing
            final File jniLibraryPathEntry = getLayout().getLibDirectory(getTargetDirectory(),
                    getMavenProject().getArtifactId(), getMavenProject().getVersion(), getAOL().toString(),
                    Library.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);
            }

            final File sharedLibraryPathEntry = getLayout().getLibDirectory(getTargetDirectory(),
                    getMavenProject().getArtifactId(), getMavenProject().getVersion(), getAOL().toString(),
                    Library.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
            final String narFile = "target/" + this.project.getArtifactId() + "-" + this.project.getVersion()
                    + ".jar";
            getLog().debug("Adding to surefire test classpath: " + narFile);
            surefireBooter.addClassPathUrl(narFile);
        }

        final List dependencies = getNarArtifacts(); // TODO: get seems heavy, not
                                                     // sure if we can push this
                                                     // up to before the fork to
                                                     // use it multiple times.
        for (final Iterator i = dependencies.iterator(); i.hasNext();) {
            final 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
            final String[] bindings = { Library.SHARED, Library.JNI };
            for (final String binding2 : bindings) {
                final String binding = binding2;
                if (!binding.equals(Library.STATIC)) {
                    final File depLibPathEntry = getLayout().getLibDirectory(getUnpackDirectory(),
                            dependency.getArtifactId(), dependency.getVersion(), getAOL().toString(), 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(), this.environmentVariables, getOS());
        }

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

        fork.setArgLine(this.argLine);

        fork.setEnvironmentVariables(this.environmentVariables);

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

            fork.setDebug(true);
        }

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

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

    surefireBooter.setForkedProcessTimeoutInSeconds(this.forkedProcessTimeoutInSeconds);

    surefireBooter.setRedirectTestOutputToFile(this.redirectTestOutputToFile);

    surefireBooter.setForkConfiguration(fork);

    surefireBooter.setChildDelegation(this.childDelegation);

    surefireBooter.setEnableAssertions(this.enableAssertions);

    surefireBooter.setReportsDirectory(this.reportsDirectory);

    addReporters(surefireBooter, fork.isForking());

    return surefireBooter;
}

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

License:Apache License

/**
 * Install the packages in application server.
 * /*  w ww  . j  a  v a 2 s . c o  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.
 *//*from w  w  w . j a  va  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.Exception.java

License:Apache License

private boolean currentProjectDependencyMatches(Artifact artifact, Artifact projectArtifact) {
    VersionRange versionRange = projectArtifact.getVersionRange();
    ArtifactVersion version;/*from   w  w w  . j a va2 s .  co m*/

    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:npanday.executable.impl.MatchPolicyFactory.java

License:Apache License

public static ExecutableMatchPolicy createExecutableVersionPolicy(final String requiredExecutableVersion) {
    return new ExecutableMatchPolicy() {
        public boolean match(ExecutableCapability executableCapability) {
            // if not specified, all versions are valid
            if (isNullOrEmpty(requiredExecutableVersion))
                return true;

            String offeredExecutableVersion = executableCapability.getExecutableVersion();

            // if not specified, it is valid for all versions!
            if (isNullOrEmpty(offeredExecutableVersion))
                return true;

            String required = requiredExecutableVersion.toLowerCase().trim();
            offeredExecutableVersion = offeredExecutableVersion.toLowerCase().trim();
            try {
                VersionRange range = VersionRange.createFromVersionSpec(offeredExecutableVersion);
                return range.containsVersion(new DefaultArtifactVersion(required));
            } catch (InvalidVersionSpecificationException e) {
                // fallback to just matching version if not a valid range
                return required.equals(offeredExecutableVersion);
            }/*w  w  w  . j a v a 2s  .co  m*/
        }

        public String toString() {
            return "ExecutableMatchPolicy[executableVersion: '" + requiredExecutableVersion + "']";
        }
    };
}

From source file:org.apache.felix.karaf.tooling.features.GenerateFeaturesFileMojo.java

License:Apache License

private Artifact getReplacement(Artifact artifact) {
    String key = String.format("%s/%s", artifact.getGroupId(), artifact.getArtifactId());
    String bundle = null;//from   w  ww. j  a  v  a 2 s  . com
    for (VersionRange range : translations.get(key).keySet()) {
        try {
            if (range.containsVersion(artifact.getSelectedVersion())) {
                bundle = translations.get(key).get(range);
                break;
            }
        } catch (OverConstrainedVersionException e) {
            bundle = null;
        }
    }
    if (bundle != null) {
        String[] split = bundle.split("/");
        return factory.createArtifact(split[0], split[1], split[2], Artifact.SCOPE_PROVIDED,
                artifact.getArtifactHandler().getPackaging());
    } else {
        return null;
    }
}

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 {//w w  w.j  a  v  a2s. c  om
        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;
}