Example usage for org.apache.maven.artifact ArtifactUtils versionlessKey

List of usage examples for org.apache.maven.artifact ArtifactUtils versionlessKey

Introduction

In this page you can find the example usage for org.apache.maven.artifact ArtifactUtils versionlessKey.

Prototype

public static String versionlessKey(Artifact artifact) 

Source Link

Usage

From source file:io.fabric8.maven.hawt.app.BuildMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    File libDir = new File(assembly, "lib");
    libDir.mkdirs();//from   w w  w . ja  v  a 2s .c  o m

    File binDir = new File(assembly, "bin");
    binDir.mkdirs();

    ArrayList<String> classpath = new ArrayList<String>();

    // get sets of dependencies
    ArrayList<Artifact> artifacts = null;
    try {
        artifacts = collectClassPath();
    } catch (DependencyGraphBuilderException e) {
        throw new MojoExecutionException("Could not get classpath", e);
    }
    System.out.println(artifacts);

    // Lets first copy this project's artifact.
    if (project.getArtifact().getFile() != null) {
        File target = new File(libDir, project.getArtifact().getFile().getName());
        classpath.add(target.getName());
        try {
            FileUtils.copyFile(project.getArtifact().getFile(), target);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not copy artifact to lib dir", e);
        }
    }

    // Artifacts in this map point to resolved files.
    Map artifactMap = project.getArtifactMap();

    // Lets then copy the it's dependencies.
    for (Artifact x : artifacts) {

        // x is not resolved, so lets look it up in the map.
        Artifact artifact = (Artifact) artifactMap.get(ArtifactUtils.versionlessKey(x));
        if (artifact == null || artifact.getFile() == null) {
            continue;
        }
        File file = artifact.getFile().getAbsoluteFile();
        try {

            File target = new File(libDir, file.getName());

            // just in case we run into an lib name collision, lets
            // find a non-colliding target name
            int dupCounter = 1;
            while (classpath.contains(target.getName())) {
                target = new File(libDir, "dup" + dupCounter + "-" + file.getName());
                dupCounter++;
            }

            classpath.add(target.getName());
            FileUtils.copyFile(artifact.getFile(), target);

        } catch (IOException e) {
            throw new MojoExecutionException("Could not copy artifact to lib dir", e);
        }
    }

    // Finally lets write the classpath.
    try {
        String classpathTxt = StringUtils.join(classpath.iterator(), "\n") + "\n";
        FileUtils.fileWrite(new File(libDir, "classpath"), classpathTxt);
    } catch (IOException e) {
        throw new MojoExecutionException("Could create the classpath file", e);
    }

    HashMap<String, String> interpolations = new HashMap<String, String>();
    // Be sure that an empty string is replaced when no main class is given
    interpolations.put("hawtapp.mvn.main.property", javaMainClass != null ? javaMainClass : "");

    File targetRun = new File(binDir, "run.sh");
    copyResource("bin/run.sh", targetRun, interpolations);
    chmodExecutable(targetRun);

    if (source != null && source.exists()) {
        try {
            FileUtils.copyDirectoryStructure(source, assembly);
        } catch (IOException e) {
            throw new MojoExecutionException("Could copy the hawt-app resources", e);
        }
    }

    ((TarArchiver) archiver).setCompression(TarArchiver.TarCompressionMethod.gzip);
    archiver.setDestFile(archive);
    archiver.addFileSet(fileSet(assembly).prefixed(archivePrefix).includeExclude(null, new String[] { "bin/*" })
            .includeEmptyDirs(true));
    archiver.setFileMode(0755);
    archiver.addFileSet(fileSet(assembly).prefixed(archivePrefix).includeExclude(new String[] { "bin/*" }, null)
            .includeEmptyDirs(true));
    try {
        archiver.createArchive();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not create the " + archive + " file", e);
    }
    projectHelper.attachArtifact(project, "tar.gz", archiveClassifier, archive);
}

From source file:io.sarl.maven.compiler.CompileMojo.java

License:Apache License

private Set<String> findSARLLibrary(ArtifactVersion compilerVersion, ArtifactVersion maxCompilerVersion,
        StringBuilder classpath, boolean enableTycho) throws MojoExecutionException, MojoFailureException {
    final String sarlLibGroupId = this.mavenHelper.getConfig("sarl-lib.groupId"); //$NON-NLS-1$
    final String sarlLibArtifactId = this.mavenHelper.getConfig("sarl-lib.artifactId"); //$NON-NLS-1$
    final String sarlLibGroupIdTycho = "p2.eclipse-plugin"; //$NON-NLS-1$
    final String sarlLibArtifactIdTycho = this.mavenHelper.getConfig("sarl-lib.osgiBundleId"); //$NON-NLS-1$
    final Set<String> foundVersions = new TreeSet<>();
    for (final Artifact dep : this.mavenHelper.getSession().getCurrentProject().getArtifacts()) {
        getLog().debug(Locale.getString(CompileMojo.class, "SCANNING_DEPENDENCY", //$NON-NLS-1$
                dep.getGroupId(), dep.getArtifactId(), dep.getVersion()));
        if (classpath.length() > 0) {
            classpath.append(":"); //$NON-NLS-1$
        }/* w  ww .  j  av a 2s  .  com*/
        classpath.append(ArtifactUtils.versionlessKey(dep));
        String gid = null;
        String aid = null;
        if (sarlLibGroupId.equals(dep.getGroupId()) && sarlLibArtifactId.equals(dep.getArtifactId())) {
            gid = sarlLibGroupId;
            aid = sarlLibArtifactId;
        } else if (enableTycho && sarlLibGroupIdTycho.equals(dep.getGroupId())
                && sarlLibArtifactIdTycho.equals(dep.getArtifactId())) {
            gid = sarlLibGroupIdTycho;
            aid = sarlLibArtifactIdTycho;
        }
        if (gid != null && aid != null) {
            final ArtifactVersion dependencyVersion = new DefaultArtifactVersion(dep.getVersion());
            if (!containsVersion(dependencyVersion, compilerVersion, maxCompilerVersion)) {
                final String shortMessage = Locale.getString(CompileMojo.class, "INCOMPATIBLE_VERSION_SHORT", //$NON-NLS-1$
                        gid, aid, dependencyVersion.toString(), compilerVersion.toString(),
                        maxCompilerVersion.toString());
                final String longMessage = Locale.getString(CompileMojo.class, "INCOMPATIBLE_VERSION_LONG", //$NON-NLS-1$
                        sarlLibGroupId, sarlLibArtifactId, dependencyVersion.toString(),
                        compilerVersion.toString(), maxCompilerVersion.toString());
                throw new MojoFailureException(this, shortMessage, longMessage);
            }
            foundVersions.add(dep.getVersion());
        }
    }
    return foundVersions;
}

From source file:org.apache.felix.scrplugin.mojo.MavenJavaClassDescriptorManager.java

License:Apache License

protected Map<String, Component> getComponentDescriptors() throws SCRDescriptorException {
    if (this.componentDescriptions == null) {
        this.componentDescriptions = new HashMap<String, Component>();

        // and now scan artifacts
        final List<Component> components = new ArrayList<Component>();
        @SuppressWarnings("unchecked")
        final Map<String, Artifact> resolved = project.getArtifactMap();
        final Iterator<Artifact> it = resolved.values().iterator();
        while (it.hasNext()) {
            final Artifact declared = it.next();
            this.log.debug("Checking artifact " + declared);
            if (this.isJavaArtifact(declared)) {
                if (Artifact.SCOPE_COMPILE.equals(declared.getScope())
                        || Artifact.SCOPE_RUNTIME.equals(declared.getScope())
                        || Artifact.SCOPE_PROVIDED.equals(declared.getScope())) {
                    this.log.debug("Resolving artifact " + declared);
                    final Artifact artifact = resolved.get(ArtifactUtils.versionlessKey(declared));
                    if (artifact != null) {
                        this.log.debug("Trying to get manifest from artifact " + artifact);
                        try {
                            final Manifest manifest = this.getManifest(artifact);
                            if (manifest != null) {
                                // read Service-Component entry
                                if (manifest.getMainAttributes()
                                        .getValue(Constants.SERVICE_COMPONENT) != null) {
                                    final String serviceComponent = manifest.getMainAttributes()
                                            .getValue(Constants.SERVICE_COMPONENT);
                                    this.log.debug("Found Service-Component: " + serviceComponent
                                            + " in artifact " + artifact);
                                    final StringTokenizer st = new StringTokenizer(serviceComponent, ",");
                                    while (st.hasMoreTokens()) {
                                        final String entry = st.nextToken().trim();
                                        if (entry.length() > 0) {
                                            final Components c = this.readServiceComponentDescriptor(artifact,
                                                    entry);
                                            if (c != null) {
                                                components.addAll(c.getComponents());
                                            }
                                        }
                                    }/*from   ww w .j  a  v  a  2 s  . c  o m*/
                                } else {
                                    this.log.debug(
                                            "Artifact has no service component entry in manifest " + artifact);
                                }
                            } else {
                                this.log.debug("Unable to get manifest from artifact " + artifact);
                            }
                        } catch (IOException ioe) {
                            throw new SCRDescriptorException("Unable to get manifest from artifact",
                                    artifact.toString(), 0, ioe);
                        }
                        this.log.debug("Trying to get scrinfo from artifact " + artifact);
                        // now read the scr private file - components stored there overwrite components already
                        // read from the service component section.
                        InputStream scrInfoFile = null;
                        try {
                            scrInfoFile = this.getFile(artifact, Constants.ABSTRACT_DESCRIPTOR_ARCHIV_PATH);
                            if (scrInfoFile != null) {
                                components.addAll(
                                        this.parseServiceComponentDescriptor(scrInfoFile).getComponents());
                            } else {
                                this.log.debug("Artifact has no scrinfo file (it's optional): " + artifact);
                            }
                        } catch (IOException ioe) {
                            throw new SCRDescriptorException("Unable to get scrinfo from artifact",
                                    artifact.toString(), 0, ioe);
                        } finally {
                            if (scrInfoFile != null) {
                                try {
                                    scrInfoFile.close();
                                } catch (IOException ignore) {
                                }
                            }
                        }
                    } else {
                        this.log.debug("Unable to resolve artifact " + declared);
                    }
                } else {
                    this.log.debug("Artifact " + declared + " has not scope compile or runtime, but "
                            + declared.getScope());
                }
            } else {
                this.log.debug(
                        "Artifact " + declared + " is not a java artifact, type is " + declared.getType());
            }
        }
        // now create map with component descriptions
        for (final Component component : components) {
            this.componentDescriptions.put(component.getImplementation().getClassame(), component);
        }
    }

    return this.componentDescriptions;
}

From source file:org.apache.sling.maven.projectsupport.DisplayBundleUpdatesMojo.java

License:Apache License

private void logUpdates(Map<Dependency, ArtifactVersions> updates) {
    List<String> withUpdates = new ArrayList<String>();
    List<String> usingCurrent = new ArrayList<String>();
    for (ArtifactVersions versions : updates.values()) {
        String left = "  " + ArtifactUtils.versionlessKey(versions.getArtifact()) + " ";
        final String current = versions.isCurrentVersionDefined() ? versions.getCurrentVersion().toString()
                : versions.getArtifact().getVersionRange().toString();
        ArtifactVersion latest = versions.getNewestUpdate(UpdateScope.ANY, Boolean.TRUE.equals(allowSnapshots));
        if (latest != null && !versions.isCurrentVersionDefined()) {
            if (versions.getArtifact().getVersionRange().containsVersion(latest)) {
                latest = null;//w  w  w  .j  ava  2 s.  c  om
            }
        }
        String right = " " + (latest == null ? current : current + " -> " + latest.toString());
        List<String> t = latest == null ? usingCurrent : withUpdates;
        if (right.length() + left.length() + 3 > INFO_PAD_SIZE) {
            t.add(left + "...");
            t.add(StringUtils.leftPad(right, INFO_PAD_SIZE));

        } else {
            t.add(StringUtils.rightPad(left, INFO_PAD_SIZE - right.length(), ".") + right);
        }
    }

    if (usingCurrent.isEmpty() && !withUpdates.isEmpty()) {
        getLog().info("No bundles are using the newest version.");
        getLog().info("");
    } else if (!usingCurrent.isEmpty()) {
        getLog().info("The following bundles are using the newest version:");
        for (String str : usingCurrent) {
            getLog().info(str);
        }
        getLog().info("");
    }
    if (withUpdates.isEmpty() && !usingCurrent.isEmpty()) {
        getLog().info("No bundles have newer versions.");
        getLog().info("");
    } else if (!withUpdates.isEmpty()) {
        getLog().info("The following bundles have newer versions:");
        for (String str : withUpdates) {
            getLog().info(str);
        }
        getLog().info("");
    }
}

From source file:org.apache.tuscany.maven.bundle.plugin.BundlesMetaDataBuildMojo.java

License:Apache License

private void generateEquinoxLauncherManifestJar(ProjectSet jarNames, File root, Log log) throws Exception {
    String equinoxLauncher = "org.apache.tuscany.sca:tuscany-node-launcher-equinox";
    Artifact artifact = (Artifact) project.getArtifactMap().get(equinoxLauncher);
    if (artifact == null) {
        return;/* w  ww.ja v a 2 s.  c  o  m*/
    }
    Set artifacts = resolveTransitively(artifact).getArtifacts();
    File feature = new File(root, "../" + featuresName + "/");
    feature.mkdirs();
    File mfJar = new File(feature, equinoxManifestJarName);
    log.info("Generating equinox manifest jar: " + mfJar.getCanonicalPath());
    FileOutputStream fos = new FileOutputStream(mfJar);
    Manifest mf = new Manifest();
    StringBuffer cp = new StringBuffer();
    String path = "../" + root.getName();

    for (Object o : artifacts) {
        Artifact a = (Artifact) o;
        if (!Artifact.SCOPE_TEST.equals(a.getScope())) {
            String id = ArtifactUtils.versionlessKey(a);
            String jar = jarNames.artifactToNameMap.get(id);
            if (jar != null) {
                cp.append(path).append('/').append(jar).append(' ');
            }
        }
    }
    if (cp.length() > 0) {
        cp.deleteCharAt(cp.length() - 1);
    }
    Attributes attrs = mf.getMainAttributes();
    attrs.putValue("Manifest-Version", "1.0");
    attrs.putValue("Implementation-Title", artifact.getId());
    attrs.putValue("Implementation-Vendor", "The Apache Software Foundation");
    attrs.putValue("Implementation-Vendor-Id", "org.apache");
    attrs.putValue("Implementation-Version", artifact.getVersion());
    attrs.putValue("Class-Path", cp.toString());
    attrs.putValue("Main-Class", "org.apache.tuscany.sca.node.equinox.launcher.NodeMain");
    JarOutputStream jos = new JarOutputStream(fos, mf);
    addFileToJar(jos, "META-INF/LICENSE", getClass().getResource("LICENSE.txt"));
    addFileToJar(jos, "META-INF/NOTICE", getClass().getResource("NOTICE.txt"));
    jos.close();
}

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

License:Apache License

private void addProvider(OSGiSurefireBooter surefireBooter, String provider, String version,
        Artifact filteredArtifact) throws ArtifactNotFoundException, ArtifactResolutionException {
    Artifact providerArtifact = artifactFactory.createDependencyArtifact("org.apache.maven.surefire", provider,
            VersionRange.createFromVersion(version), "jar", null, Artifact.SCOPE_TEST);
    ArtifactResolutionResult result = resolveArtifact(filteredArtifact, providerArtifact);

    for (Iterator i = result.getArtifacts().iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();

        String key = ArtifactUtils.versionlessKey(artifact);
        if ("junit:junit".equals(key) || "jnuit:junit-dep".equals(key)) {
            // Skip junit as it will be pulled from the test case dependencies
            continue;
        }//from   ww w  . j a va2  s  .c  o  m
        getLog().debug("Adding to surefire test classpath: " + artifact.getFile().getAbsolutePath());

        surefireBooter.addSurefireClassPathUrl(artifact.getFile().getAbsolutePath());
    }
}

From source file:org.codehaus.mojo.cassandra.AbstractCassandraMojo.java

License:Apache License

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for
 * all classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param jarFile   The jar file to create/update
 * @param mainClass The main class to run.
 * @throws java.io.IOException if something went wrong.
 *//*from w w  w. j  av a  2 s .  c o m*/
protected void createCassandraJar(File jarFile, String mainClass, File cassandraDir) throws IOException {
    File conf = new File(cassandraDir, "conf");
    FileOutputStream fos = null;
    JarOutputStream jos = null;
    try {
        fos = new FileOutputStream(jarFile);
        jos = new JarOutputStream(fos);
        jos.setLevel(JarOutputStream.STORED);
        jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF"));

        Manifest man = new Manifest();

        // we can't use StringUtils.join here since we need to add a '/' to
        // the end of directory entries - otherwise the jvm will ignore them.
        StringBuilder cp = new StringBuilder();
        cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');
        getLog().debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(pluginArtifact)
                + " to the classpath");
        cp.append(new URL(pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        for (Artifact artifact : this.pluginDependencies) {
            getLog().debug("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact)
                    + " to the classpath");
            // NOTE: if File points to a directory, this entry MUST end in '/'.
            cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
            cp.append(' ');
        }

        if (addMainClasspath || addTestClasspath) {
            if (addTestClasspath) {
                getLog().debug("Adding: " + testClassesDirectory + " to the classpath");
                cp.append(new URL(testClassesDirectory.toURI().toASCIIString()).toExternalForm());
                cp.append(' ');
            }
            if (addMainClasspath) {
                getLog().debug("Adding: " + classesDirectory + " to the classpath");
                cp.append(new URL(classesDirectory.toURI().toASCIIString()).toExternalForm());
                cp.append(' ');
            }
            for (Artifact artifact : (Set<Artifact>) this.project.getArtifacts()) {
                if ("jar".equals(artifact.getType()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                        && (!Artifact.SCOPE_TEST.equals(artifact.getScope()) || addTestClasspath)) {
                    getLog().debug("Adding dependency: " + ArtifactUtils.versionlessKey(artifact)
                            + " to the classpath");
                    // NOTE: if File points to a directory, this entry MUST end in '/'.
                    cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
                    cp.append(' ');
                }
            }
        }

        man.getMainAttributes().putValue("Manifest-Version", "1.0");
        man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
        man.getMainAttributes().putValue("Main-Class", mainClass);

        man.write(jos);
    } finally {
        IOUtil.close(jos);
        IOUtil.close(fos);
    }
}

From source file:org.codehaus.mojo.license.DownloadOsgiLicensesMojo.java

private Artifact resolveArtifact(MavenProject project) {
    Artifact artifact = project.getArtifact();
    String key = ArtifactUtils.versionlessKey(artifact);
    artifact = (Artifact) this.project.getArtifactMap().get(key);
    return artifact;
}

From source file:org.codehaus.mojo.pluginsupport.dependency.Dependencies.java

License:Apache License

public Dependencies(final MavenProject project, final DependencyResolutionListener listener) {
    assert project != null;
    assert listener != null;

    this.projectDependencies = listener.getDependencyTree().getRootNode().getChildren();
    this.resolvedDependencies = listener;

    ////from www  .  j a v  a 2  s.  c  o m
    // Workaround to ensure proper File objects in the Artifacts from the DependencyResolutionListener
    //
    Map projectMap = new HashMap();
    Iterator iter = project.getArtifacts().iterator();

    while (iter.hasNext()) {
        Artifact artifact = (Artifact) iter.next();
        projectMap.put(ArtifactUtils.versionlessKey(artifact), artifact);
    }

    mapArtifactFiles(listener.getDependencyTree().getRootNode(), projectMap);
}

From source file:org.codehaus.mojo.pluginsupport.dependency.Dependencies.java

License:Apache License

private void mapArtifactFiles(final Node node, final Map projectMap) {
    assert node != null;
    assert projectMap != null;

    List childs = node.getChildren();
    if ((childs == null) || childs.isEmpty()) {
        return;/*from w  ww.  j a  v a  2  s . co m*/
    }

    Iterator iter = childs.iterator();
    while (iter.hasNext()) {
        Node anode = (Node) iter.next();
        String key = ArtifactUtils.versionlessKey(anode.getArtifact());
        Artifact projartifact = (Artifact) projectMap.get(key);
        if (projartifact != null) {
            anode.getArtifact().setFile(projartifact.getFile());
        }

        mapArtifactFiles(anode, projectMap);
    }
}