Example usage for org.apache.maven.artifact Artifact getMetadataList

List of usage examples for org.apache.maven.artifact Artifact getMetadataList

Introduction

In this page you can find the example usage for org.apache.maven.artifact Artifact getMetadataList.

Prototype

Collection<ArtifactMetadata> getMetadataList();

Source Link

Usage

From source file:hudson.maven.artifact.deployer.DefaultArtifactDeployer.java

License:Apache License

public void deploy(File source, Artifact artifact, ArtifactRepository deploymentRepository,
        ArtifactRepository localRepository) throws ArtifactDeploymentException {

    // If we're installing the POM, we need to transform it first. The source file supplied for 
    // installation here may be the POM, but that POM may not be set as the file of the supplied
    // artifact. Since the transformation only has access to the artifact and not the supplied
    // source file, we have to use the Artifact.setFile(..) and Artifact.getFile(..) methods
    // to shunt the POM file into the transformation process.
    // Here, we also set a flag indicating that the POM has been shunted through the Artifact,
    // and to expect the transformed version to be available in the Artifact afterwards...
    boolean useArtifactFile = false;
    File oldArtifactFile = artifact.getFile();
    if ("pom".equals(artifact.getType())) {
        artifact.setFile(source);//from www.java2s . c  om
        useArtifactFile = true;
    }

    try {
        transformationManager.transformForDeployment(artifact, deploymentRepository, localRepository);

        // If we used the Artifact shunt to transform a POM source file, we need to install
        // the transformed version, not the supplied version. Therefore, we need to replace
        // the supplied source POM with the one from Artifact.getFile(..).
        if (useArtifactFile) {
            source = artifact.getFile();
            artifact.setFile(oldArtifactFile);
        }

        // FIXME: Why oh why are we re-installing the artifact in the local repository? Isn't this
        // the responsibility of the ArtifactInstaller??

        // Copy the original file to the new one if it was transformed
        File artifactFile = new File(localRepository.getBasedir(), localRepository.pathOf(artifact));
        if (!artifactFile.equals(source)) {
            FileUtils.copyFile(source, artifactFile);
        }
        //FIXME find a way to get hudson BuildListener ??
        TransferListener downloadMonitor = new TransferListener() {

            public void transferInitiated(TransferEvent transferEvent) {
                String message = transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "Uploading"
                        : "Downloading";

                String url = transferEvent.getWagon().getRepository().getUrl();

                // TODO: can't use getLogger() because this isn't currently instantiated as a component
                System.out.println(message + ": " + url + "/" + transferEvent.getResource().getName());
            }

            public void transferStarted(TransferEvent transferEvent) {
                // no op
            }

            public void transferProgress(TransferEvent transferEvent, byte[] buffer, int length) {
                // no op
            }

            public void transferCompleted(TransferEvent transferEvent) {
                long contentLength = transferEvent.getResource().getContentLength();
                if (contentLength != WagonConstants.UNKNOWN_LENGTH) {
                    String type = (transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "uploaded"
                            : "downloaded");
                    String l = contentLength >= 1024 ? (contentLength / 1024) + "K" : contentLength + "b";
                    System.out.println(l + " " + type);
                }

            }

            public void transferError(TransferEvent transferEvent) {
                transferEvent.getException().printStackTrace();
            }

            public void debug(String message) {
                // TODO Auto-generated method stub

            }

        };
        wagonManager.putArtifact(source, artifact, deploymentRepository, downloadMonitor);

        // must be after the artifact is installed
        for (Iterator i = artifact.getMetadataList().iterator(); i.hasNext();) {
            ArtifactMetadata metadata = (ArtifactMetadata) i.next();
            repositoryMetadataManager.deploy(metadata, localRepository, deploymentRepository);
        }
        // TODO: would like to flush this, but the plugin metadata is added in advance, not as an install/deploy transformation
        // This would avoid the need to merge and clear out the state during deployment
        //            artifact.getMetadataList().clear();
    } catch (TransferFailedException e) {
        throw new ArtifactDeploymentException("Error deploying artifact: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ArtifactDeploymentException("Error deploying artifact: " + e.getMessage(), e);
    } catch (RepositoryMetadataDeploymentException e) {
        throw new ArtifactDeploymentException("Error installing artifact's metadata: " + e.getMessage(), e);
    }
}

From source file:net.md_5.specialsource.mavenplugin.InstallRemappedFileMojo.java

License:Apache License

/**
 * Installs the checksums for the specified artifact if this has been enabled in the plugin configuration. This
 * method creates checksums for files that have already been installed to the local repo to account for on-the-fly
 * generated/updated files. For example, in Maven 2.0.4- the <code>ProjectArtifactMetadata</code> did not install
 * the original POM file (cf. MNG-2820). While the plugin currently requires Maven 2.0.6, we continue to hash the
 * installed POM for robustness with regard to future changes like re-introducing some kind of POM filtering.
 *
 * @param artifact The artifact for which to create checksums, must not be <code>null</code>.
 * @param metadataFiles The set where additional metadata files will be registered for later checksum installation,
 *            must not be <code>null</code>.
 * @throws MojoExecutionException If the checksums could not be installed.
 *///  w w  w. j  a va 2 s  .c  om
protected void installChecksums(Artifact artifact, Collection metadataFiles) throws MojoExecutionException {
    if (!createChecksum) {
        return;
    }

    File artifactFile = getLocalRepoFile(artifact);
    installChecksums(artifactFile);

    Collection metadatas = artifact.getMetadataList();
    if (metadatas != null) {
        for (Iterator it = metadatas.iterator(); it.hasNext();) {
            ArtifactMetadata metadata = (ArtifactMetadata) it.next();
            File metadataFile = getLocalRepoFile(metadata);
            metadataFiles.add(metadataFile);
        }
    }
}

From source file:npanday.plugin.libraryimporter.install.AbstractInstallMojo.java

License:Apache License

/**
 * Installs the checksums for the specified artifact (and its metadata files) if this has been enabled in the plugin
 * configuration. This method creates checksums for files that have already been installed to the local repo to
 * account for on-the-fly generated/updated files. For example, in Maven 2.0.4- the
 * <code>ProjectArtifactMetadata</code> did not install the original POM file (cf. MNG-2820). While the plugin
 * currently requires Maven 2.0.6, we continue to hash the installed POM for robustness with regard to future
 * changes like re-introducing some kind of POM filtering.
 *
 * @param artifact The artifact for which to create checksums, must not be <code>null</code>.
 * @throws MojoExecutionException If the checksums could not be installed.
 *//*w  w  w.  ja v  a2s. c o m*/
protected void installChecksums(Artifact artifact) throws MojoExecutionException {
    if (!createChecksums) {
        return;
    }

    File artifactFile = getLocalRepoFile(artifact);
    installChecksums(artifactFile);

    Collection metadatas = artifact.getMetadataList();
    if (metadatas != null) {
        for (Iterator it = metadatas.iterator(); it.hasNext();) {
            ArtifactMetadata metadata = (ArtifactMetadata) it.next();
            File metadataFile = getLocalRepoFile(metadata);
            installChecksums(metadataFile);
        }
    }
}

From source file:org.jfrog.build.extractor.maven.BuildInfoRecorder.java

License:Apache License

private void addArtifactsToCurrentModule(MavenProject project, ModuleBuilder module) {
    Set<Artifact> moduleArtifacts = currentModuleArtifacts.get();
    if (moduleArtifacts == null) {
        logger.warn(/*from  w  w  w .  j av  a  2  s  .c o  m*/
                "Skipping Artifactory Build-Info module artifact addition: Null current module artifact list.");
        return;
    }

    ArtifactoryClientConfiguration.PublisherHandler publisher = conf.publisher;
    IncludeExcludePatterns patterns = new IncludeExcludePatterns(publisher.getIncludePatterns(),
            publisher.getExcludePatterns());
    boolean excludeArtifactsFromBuild = publisher.isFilterExcludedArtifactsFromBuild();

    boolean pomFileAdded = false;
    Artifact nonPomArtifact = null;
    String pomFileName = null;

    for (Artifact moduleArtifact : moduleArtifacts) {
        String artifactId = moduleArtifact.getArtifactId();
        String artifactVersion = moduleArtifact.getVersion();
        String artifactClassifier = moduleArtifact.getClassifier();
        String artifactExtension = moduleArtifact.getArtifactHandler().getExtension();
        String type = getTypeString(moduleArtifact.getType(), artifactClassifier, artifactExtension);

        String artifactName = getArtifactName(artifactId, artifactVersion, artifactClassifier,
                artifactExtension);

        ArtifactBuilder artifactBuilder = new ArtifactBuilder(artifactName).type(type);
        File artifactFile = moduleArtifact.getFile();

        if ("pom".equals(type)) {
            pomFileAdded = true;
            // For pom projects take the file from the project if the artifact file is null.
            if (moduleArtifact.equals(project.getArtifact())) {
                artifactFile = project.getFile(); // project.getFile() returns the project pom file
            }
        } else if (moduleArtifact.getMetadataList().size() > 0) {
            nonPomArtifact = moduleArtifact;
            pomFileName = StringUtils.removeEnd(artifactName, artifactExtension) + "pom";
        }

        org.jfrog.build.api.Artifact artifact = artifactBuilder.build();
        String groupId = moduleArtifact.getGroupId();
        String deploymentPath = getDeploymentPath(groupId, artifactId, artifactVersion, artifactClassifier,
                artifactExtension);
        // If excludeArtifactsFromBuild and the PatternMatcher found conflict, add the excluded artifact to the excluded artifact set.
        if (excludeArtifactsFromBuild && PatternMatcher.pathConflicts(deploymentPath, patterns)) {
            module.addExcludedArtifact(artifact);
        } else {
            module.addArtifact(artifact);
        }
        if (isPublishArtifacts(artifactFile)) {
            addDeployableArtifact(artifact, artifactFile, moduleArtifact.getGroupId(), artifactId,
                    artifactVersion, artifactClassifier, artifactExtension);
        }
    }
    /*
     * In case of non packaging Pom project module, we need to create the pom file from the ProjectArtifactMetadata on the Artifact
     */
    if (!pomFileAdded && nonPomArtifact != null) {
        String deploymentPath = getDeploymentPath(nonPomArtifact.getGroupId(), nonPomArtifact.getArtifactId(),
                nonPomArtifact.getVersion(), nonPomArtifact.getClassifier(), "pom");

        addPomArtifact(nonPomArtifact, module, patterns, deploymentPath, pomFileName,
                excludeArtifactsFromBuild);
    }
}

From source file:org.jfrog.build.extractor.maven.BuildInfoRecorder.java

License:Apache License

private void addPomArtifact(Artifact nonPomArtifact, ModuleBuilder module, IncludeExcludePatterns patterns,
        String deploymentPath, String pomFileName, boolean excludeArtifactsFromBuild) {

    for (ArtifactMetadata metadata : nonPomArtifact.getMetadataList()) {
        if (metadata instanceof ProjectArtifactMetadata) { // The pom metadata
            ArtifactBuilder artifactBuilder = new ArtifactBuilder(pomFileName).type("pom");
            File pomFile = ((ProjectArtifactMetadata) metadata).getFile();
            org.jfrog.build.api.Artifact pomArtifact = artifactBuilder.build();

            if (excludeArtifactsFromBuild && PatternMatcher.pathConflicts(deploymentPath, patterns)) {
                module.addExcludedArtifact(pomArtifact);
            } else {
                module.addArtifact(pomArtifact);
            }//  w w  w.java  2s .c  o  m
            if (isPublishArtifacts(pomFile)) {
                addDeployableArtifact(pomArtifact, pomFile, nonPomArtifact.getGroupId(),
                        nonPomArtifact.getArtifactId(), nonPomArtifact.getVersion(),
                        nonPomArtifact.getClassifier(), "pom");
            }
            break;
        }
    }
}

From source file:org.org.maven.plugin.dws.utils.RepositoryUtils.java

License:Apache License

/**
 * @param artifact not null//from  w  w w . java2 s. c  o  m
 * @param repo not null
 * @return the artifact url in the given repo for the given artifact. If it is a snapshot artifact, the version
 * will be the timestamp and the build number from the metadata. Could return null if the repo is blacklisted.
 */
public String getDependencyUrlFromRepository(Artifact artifact, ArtifactRepository repo) {
    if (repo.isBlacklisted()) {
        return null;
    }

    Artifact copyArtifact = ArtifactUtils.copyArtifact(artifact);
    // Try to get the last artifact repo name depending the snapshot version
    if ((artifact.isSnapshot() && repo.getSnapshots().isEnabled())) {
        if (artifact.getBaseVersion().equals(artifact.getVersion())) {
            // Try to resolve it if not already done
            if (artifact.getMetadataList() == null || artifact.getMetadataList().isEmpty()) {
                try {
                    resolve(artifact);
                } catch (ArtifactResolutionException e) {
                    log.error("Artifact: " + artifact.getId() + " could not be resolved.");
                } catch (ArtifactNotFoundException e) {
                    log.error("Artifact: " + artifact.getId() + " was not found.");
                }
            }

            for (Iterator it = artifact.getMetadataList().iterator(); it.hasNext();) {
                ArtifactMetadata m = (ArtifactMetadata) it.next();

                if (m instanceof SnapshotArtifactRepositoryMetadata) {
                    SnapshotArtifactRepositoryMetadata snapshotMetadata = (SnapshotArtifactRepositoryMetadata) m;

                    // Removed not found log
                    int oldThreshold = loggerManager.getThreshold();
                    loggerManager.setThreshold(RepositoryMetadataManager.class.getName(),
                            Logger.LEVEL_DISABLED);
                    try {
                        repositoryMetadataManager.resolveAlways(snapshotMetadata, localRepository, repo);
                    } catch (RepositoryMetadataResolutionException e) {
                        loggerManager.setThreshold(RepositoryMetadataManager.class.getName(), oldThreshold);
                        if (log.isDebugEnabled()) {
                            log.error("Unable to connect to: " + repo.getUrl(), e);
                        } else {
                            log.error("Unable to connect to: " + repo.getUrl());
                        }
                        return repo.getUrl() + "/" + repo.pathOf(copyArtifact);
                    } finally {
                        loggerManager.setThreshold(RepositoryMetadataManager.class.getName(), oldThreshold);
                    }

                    Metadata metadata = snapshotMetadata.getMetadata();
                    if (metadata.getVersioning() == null || metadata.getVersioning().getSnapshot() == null
                            || metadata.getVersioning().getSnapshot().isLocalCopy()
                            || metadata.getVersioning().getSnapshot().getTimestamp() == null) {
                        continue;
                    }

                    // create the version according SnapshotTransformation
                    String version = StringUtils.replace(copyArtifact.getVersion(), Artifact.SNAPSHOT_VERSION,
                            metadata.getVersioning().getSnapshot().getTimestamp()) + "-"
                            + metadata.getVersioning().getSnapshot().getBuildNumber();
                    copyArtifact.setVersion(version);
                }
            }
        }
    }

    return repo.getUrl() + "/" + repo.pathOf(copyArtifact);
}

From source file:org.sonatype.nexus.maven.staging.deploy.strategy.AbstractDeployStrategy.java

License:Open Source License

/**
 * Performs an "install" (not to be confused with "install into local repository!) into the staging repository. It
 * will retain snapshot versions, and no metadata is created at all. In short: performs a simple file copy.
 * <p/>//from w ww.  j a v a  2  s .co  m
 * This one single method is not thread safe, as it performs IO and appends to the "index" file. Hence, this
 * one method is execute in a synchronized block of a static object's monitor, to prevent multiple parallel
 * install actions to happen. As install is local FS operation, this method should quickly finish it's job
 * as costly operations (like asking for Staging profile of REST API of remote Nexus) already happened, we
 * do only local FS ops here.
 */
protected void install(final File source, final Artifact artifact, final ArtifactRepository stagingRepository,
        final File stagingDirectory, final ArtifactRepository remoteRepository)
        throws ArtifactInstallationException, MojoExecutionException {
    synchronized (parallelLock) {
        final String path = stagingRepository.pathOf(artifact);
        try {
            artifactInstaller.install(source, artifact, stagingRepository);

            String pluginPrefix = null;
            // String pluginName = null;
            for (ArtifactMetadata artifactMetadata : artifact.getMetadataList()) {
                if (artifactMetadata instanceof GroupRepositoryMetadata) {
                    final Plugin plugin = ((GroupRepositoryMetadata) artifactMetadata).getMetadata()
                            .getPlugins().get(0);
                    pluginPrefix = plugin.getPrefix();
                    // pluginName = plugin.getName();
                }
            }

            // append the index file
            final FileOutputStream fos = new FileOutputStream(new File(stagingDirectory, ".index"), true);
            final OutputStreamWriter osw = new OutputStreamWriter(fos, "ISO-8859-1");
            final PrintWriter pw = new PrintWriter(osw);
            String pomFileName = null;
            for (ArtifactMetadata artifactMetadata : artifact.getMetadataList()) {
                if (artifactMetadata instanceof ProjectArtifactMetadata) {
                    pomFileName = (artifactMetadata).getLocalFilename(stagingRepository);
                }
            }
            pw.println(String.format("%s=%s:%s:%s:%s:%s:%s:%s:%s:%s:%s", path, artifact.getGroupId(),
                    artifact.getArtifactId(), artifact.getVersion(),
                    Strings.isNullOrEmpty(artifact.getClassifier()) ? "n/a" : artifact.getClassifier(),
                    artifact.getType(), artifact.getArtifactHandler().getExtension(),
                    Strings.isNullOrEmpty(pomFileName) ? "n/a" : pomFileName,
                    Strings.isNullOrEmpty(pluginPrefix) ? "n/a" : pluginPrefix,
                    remoteRepository != null ? remoteRepository.getId() : "n/a",
                    remoteRepository != null ? remoteRepository.getUrl() : "n/a"));
            pw.flush();
            pw.close();
        } catch (IOException e) {
            throw new ArtifactInstallationException("Cannot locally stage and maintain the index file!", e);
        }
    }
}