Example usage for org.apache.maven.artifact.deployer ArtifactDeploymentException ArtifactDeploymentException

List of usage examples for org.apache.maven.artifact.deployer ArtifactDeploymentException ArtifactDeploymentException

Introduction

In this page you can find the example usage for org.apache.maven.artifact.deployer ArtifactDeploymentException ArtifactDeploymentException.

Prototype

public ArtifactDeploymentException(String message, Throwable cause) 

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 w ww . j  ava  2 s.c o m
        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:hudson.maven.artifact.transform.SnapshotTransformation.java

License:Apache License

public void transformForDeployment(Artifact artifact, ArtifactRepository remoteRepository,
        ArtifactRepository localRepository) throws ArtifactDeploymentException {
    if (artifact.isSnapshot()) {
        Snapshot snapshot = new Snapshot();
        if (remoteRepository.isUniqueVersion()) {
            snapshot.setTimestamp(getDeploymentTimestamp());
        }//from  ww w  .j  a  va 2  s  .  co  m

        // we update the build number anyway so that it doesn't get lost. It requires the timestamp to take effect
        try {
            int buildNumber = resolveLatestSnapshotBuildNumber(artifact, localRepository, remoteRepository);

            snapshot.setBuildNumber(buildNumber + 1);
        } catch (RepositoryMetadataResolutionException e) {
            throw new ArtifactDeploymentException("Error retrieving previous build number for artifact '"
                    + artifact.getDependencyConflictId() + "': " + e.getMessage(), e);
        }

        RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact, snapshot);

        artifact.setResolvedVersion(
                constructVersion(metadata.getMetadata().getVersioning(), artifact.getBaseVersion()));

        artifact.addMetadata(metadata);
    }
}

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

License:Open Source License

/**
 * Performs "bulk" remote deploy of locally installed artifacts, and is driven by "index" file.
 *//*  w  ww  . j  av  a 2  s  .c  om*/
@Override
public void finalizeDeploy(final FinalizeDeployRequest request)
        throws ArtifactDeploymentException, MojoExecutionException {
    log.info("Deploying remotely...");
    final File stagingDirectory = request.getParameters().getDeferredDirectoryRoot();
    if (!stagingDirectory.isDirectory()) {
        log.warn("Nothing to deploy, directory \"{}\" does not exists!", stagingDirectory.getAbsolutePath());
        return;
    }

    // we do direct upload
    log.info("Bulk deploying locally gathered artifacts from directory: ");
    try {
        // prepare the local staging directory
        // we have normal deploy
        log.info(" * Bulk deploying locally gathered snapshot artifacts");
        deployUp(request.getMavenSession(), stagingDirectory, null);
        log.info(" * Bulk deploy of locally gathered snapshot artifacts finished.");
    } catch (IOException e) {
        log.error("Upload of locally deferred directory finished with a failure.");
        throw new ArtifactDeploymentException("Remote deploy failed: " + e.getMessage(), e);
    }

    log.info("Remote deploy finished with success.");
}

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

License:Open Source License

/**
 * Remote deploys the "image", using {@link #zapUp(Server, Proxy, File, String)}.
 *//*from www.jav a 2 s  . c  o  m*/
@Override
public void finalizeDeploy(final FinalizeDeployRequest request)
        throws ArtifactDeploymentException, MojoExecutionException {
    log.info("Staging remotely locally deployed repository...");
    final RemoteNexus remoteNexus = createRemoteNexus(request.getMavenSession(), request.getParameters());
    final String profileId = request.getParameters().getStagingProfileId();
    final Profile stagingProfile = remoteNexus.getStagingWorkflowV2Service().selectProfile(profileId);
    final StagingRepository stagingRepository = beforeUpload(request.getParameters(), remoteNexus,
            stagingProfile);
    try {
        log.info(" * Uploading locally staged artifacts to profile {}", stagingProfile.name());
        zapUp(remoteNexus.getServer(), remoteNexus.getProxy(),
                request.getParameters().getStagingDirectoryRoot(), stagingRepository.getUrl());
        log.info(" * Upload of locally staged artifacts finished.");
        afterUpload(request.getParameters(), remoteNexus, stagingRepository);
    } catch (Exception e) {
        afterUploadFailure(request.getParameters(), remoteNexus, Collections.singletonList(stagingRepository),
                e);
        log.error("Remote staging finished with a failure.");
        throw new ArtifactDeploymentException("Remote staging failed: " + e.getMessage(), e);
    }
    log.info("Remote staging finished with success.");
}

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

License:Open Source License

/**
 * Performs Nexus staging of locally staged artifacts.
 *///from  ww  w.j  av  a 2s .co m
@Override
public void finalizeDeploy(final FinalizeDeployRequest request)
        throws ArtifactDeploymentException, MojoExecutionException {
    log.info("Performing remote staging...");
    final File stageRoot = request.getParameters().getStagingDirectoryRoot();
    final File[] localStageRepositories = stageRoot.listFiles();
    if (localStageRepositories == null) {
        log.info("We have nothing locally staged, bailing out.");
        return;
    }
    if (request.getRemoteNexus() == null) {
        // this happens from stage-deployed mojo, where 1st pass already locally staged
        // but there is no client yet in 2nd invocation of maven
        request.setRemoteNexus(createRemoteNexus(request.getMavenSession(), request.getParameters()));
    }
    final RemoteNexus remoteNexus = request.getRemoteNexus();
    final List<StagingRepository> zappedStagingRepositories = new ArrayList<StagingRepository>();
    for (File profileDirectory : localStageRepositories) {
        if (!profileDirectory.isDirectory()) {
            continue;
        }

        // we do remote staging
        final String profileId = profileDirectory.getName();
        log.info("");
        log.info(" * Remote staging into staging profile ID \"{}\"", profileId);

        try {
            final Profile stagingProfile = remoteNexus.getStagingWorkflowV2Service().selectProfile(profileId);
            final StagingRepository stagingRepository = beforeUpload(request.getParameters(), remoteNexus,
                    stagingProfile);
            zappedStagingRepositories.add(stagingRepository);
            log.info(" * Uploading locally staged artifacts to profile {}", stagingProfile.name());
            deployUp(request.getMavenSession(),
                    getStagingDirectory(request.getParameters().getStagingDirectoryRoot(), profileId),
                    createDeploymentArtifactRepository(remoteNexus.getServer().getId(),
                            stagingRepository.getUrl()));
            log.info(" * Upload of locally staged artifacts finished.");
            afterUpload(request.getParameters(), remoteNexus, stagingRepository);
        } catch (NexusClientNotFoundException e) {
            afterUploadFailure(request.getParameters(), remoteNexus, zappedStagingRepositories, e);
            log.error("Remote staging finished with a failure: {}", e.getMessage());
            log.error("");
            log.error("Possible causes of 404 Not Found error:");
            log.error(
                    " * your local workspace is \"dirty\" with previous runs, that locally staged artifacts? Run \"mvn clean\"...");
            log.error(
                    " * remote Nexus got the profile with ID \"{}\" removed during this build? Get to Nexus admin...",
                    profileId);
            throw new ArtifactDeploymentException("Remote staging failed: " + e.getMessage(), e);
        } catch (NexusClientAccessForbiddenException e) {
            afterUploadFailure(request.getParameters(), remoteNexus, zappedStagingRepositories, e);
            log.error("Remote staging finished with a failure: {}", e.getMessage());
            log.error("");
            log.error("Possible causes of 403 Forbidden:");
            log.error(
                    " * you have no permissions to stage against profile with ID \"{}\"? Get to Nexus admin...",
                    profileId);
            throw new ArtifactDeploymentException("Remote staging failed: " + e.getMessage(), e);
        } catch (Exception e) {
            afterUploadFailure(request.getParameters(), remoteNexus, zappedStagingRepositories, e);
            log.error("Remote staging finished with a failure: {}", e.getMessage());
            throw new ArtifactDeploymentException("Remote staging failed: " + e.getMessage(), e);
        }
    }
    log.info("Remote staged {} repositories, finished with success.", zappedStagingRepositories.size());

    if (!request.getParameters().isSkipStagingRepositoryClose()
            && request.getParameters().isAutoReleaseAfterClose()) {
        releaseAfterClose(request.getParameters(), remoteNexus, zappedStagingRepositories);
    }
}

From source file:org.sonatype.nexus.plugin.deploy.AbstractDeployMojo.java

License:Open Source License

/**
 * Uploads staged artifacts.//from  w  ww .  j  a v  a 2 s.c  o m
 * 
 * @param source the file to stage
 * @param artifact the artifact definition
 * @param stagingRepository the repository to stage to
 * @param localRepository the local repository to install into
 * @throws ArtifactDeploymentException if an error occurred deploying the artifact
 */
protected void uploadStagedArtifacts() throws ArtifactDeploymentException {
    boolean successful = false;
    try {
        final String deployUrl = beforeUpload();
        final ZapperRequest request = new ZapperRequest(getStagingDirectory(), deployUrl);

        final Server server = MavenSettings.selectServer(mavenSession.getSettings(), serverId);
        if (server != null) {
            final Server dServer = MavenSettings.decrypt(secDispatcher, server);
            request.setRemoteUsername(dServer.getUsername());
            request.setRemotePassword(dServer.getPassword());
        }

        final Proxy proxy = MavenSettings.selectProxy(mavenSession.getSettings(), deployUrl);
        if (proxy != null) {
            final Proxy dProxy = MavenSettings.decrypt(secDispatcher, proxy);
            request.setProxyProtocol(dProxy.getProtocol());
            request.setProxyHost(dProxy.getHost());
            request.setProxyPort(dProxy.getPort());
            request.setProxyUsername(dProxy.getUsername());
            request.setProxyPassword(dProxy.getPassword());
        }

        LogbackUtils.syncLogLevelWithMaven(getLog());
        getLog().info("Deploying staged artifacts to: " + deployUrl);
        zapper.deployDirectory(request);
        successful = true;
    } catch (IOException e) {
        throw new ArtifactDeploymentException("Cannot deploy!", e);
    } catch (SecDispatcherException e) {
        throw new ArtifactDeploymentException("Cannot decipher credentials for deploy!", e);
    } finally {
        afterUpload(successful);
    }
}

From source file:org.sonatype.nexus.plugin.deploy.AbstractDeployMojo.java

License:Open Source License

protected String beforeUpload() throws ArtifactDeploymentException {
    if (deployUrl != null) {
        getLog().info("Performing normal upload against URL: " + deployUrl);
        return deployUrl;
    } else if (nexusUrl != null) {
        try {/* w  ww  .j a v  a 2 s  .c  om*/
            getLog().info("Initiating staging against Nexus on URL " + nexusUrl);
            createStageClient();

            final MavenProject currentProject = mavenSession.getCurrentProject();

            // if profile is not "targeted", perform a match and save the result
            if (StringUtils.isBlank(stagingProfileId)) {
                stagingProfileId = stageClient.getStageProfileForUser(currentProject.getGroupId(),
                        currentProject.getArtifactId(), currentProject.getVersion());
                getLog().info("Using staging profile ID \"" + stagingProfileId + "\" (matched by Nexus).");
            } else {
                getLog().info("Using staging profile ID \"" + stagingProfileId + "\" (configured by user).");
            }

            if (StringUtils.isBlank(stagingRepositoryId)) {
                stagingRepositoryId = stageClient.startRepository(stagingProfileId,
                        "Started by nexus-maven-plugin", tags);
                // store the one just created for us, as it means we need to "babysit" it (close or drop, depending
                // on outcome)
                createdStagingRepositoryId = stagingRepositoryId;
                if (tags != null && !tags.isEmpty()) {
                    getLog().info("Created staging repository with ID \"" + stagingRepositoryId
                            + "\", applied tags: " + tags);
                } else {
                    getLog().info("Created staging repository with ID \"" + stagingRepositoryId + "\".");
                }

            } else {
                createdStagingRepositoryId = null;
                getLog().info("Using preconfigured staging repository with ID \"" + stagingRepositoryId
                        + "\" (we are NOT managing it)."); // we will not close it! This might be created by some
                                                                                                                                                   // other automated component
            }

            return concat(nexusUrl, "/service/local/staging/deployByRepositoryId", stagingRepositoryId);
        } catch (RESTLightClientException e) {
            throw new ArtifactDeploymentException("Error before upload while managing staging repository!", e);
        }
    } else {
        throw new ArtifactDeploymentException("No deploy URL set, nor Nexus BaseURL given!");
    }
}

From source file:org.sonatype.nexus.plugin.deploy.AbstractDeployMojo.java

License:Open Source License

protected void afterUpload(final boolean successful) throws ArtifactDeploymentException {
    // in any other case nothing happens
    // by having stagingRepositoryId string non-empty, it means we created it, hence, we are managing it too
    if (createdStagingRepositoryId != null) {
        try {/*from w  w  w.j  a  v a  2s. c o  m*/
            final StageRepository repo = new StageRepository(stagingProfileId, createdStagingRepositoryId,
                    true);
            if (successful) {
                getLog().info("Closing staging repository.");
                stageClient.finishRepository(repo, description);
            } else {
                if (!keepOnFailure) {
                    getLog().info("Dropping staging repository (due to unsuccesful upload).");
                    stageClient.dropRepository(repo,
                            "Dropped by nexus-maven-plugin (due to unsuccesful upload).");
                } else {
                    getLog().info("Not dropping staging repository (due to unsuccesful upload).");
                }
            }
        } catch (RESTLightClientException e) {
            // these two lines dumps the rule errors to log
            final String responseMessage = StagingDomUtils.repositoryActionFailureMessage(e.getErrorDocument(),
                    "Failed to close staging repository!");
            getLog().error(responseMessage);
            throw new ArtifactDeploymentException(
                    "Error after upload while managing staging repository! Staging repository in question is "
                            + createdStagingRepositoryId,
                    e);
        }
    }

    // this variable will be filled in only if we really staged: is it targeted repo (someone else created or not)
    // does not matter, see managed flag
    // deployUrl perform "plain deploy", hence this will be no written out, it will be written out in any other case
    if (stagingRepositoryId != null) {
        final Properties stagingProperties = new Properties();
        // the staging repository ID where the staging went
        stagingProperties.put("stagingRepository.id", stagingRepositoryId);
        // the staging repository URL (if closed! see below)
        stagingProperties.put("stagingRepository.url",
                concat(nexusUrl, "/content/repositories", stagingRepositoryId));
        // targeted repo mode or not (are we closing it or someone else? If false, the URL above might not yet
        // exists if not yet closed....
        stagingProperties.put("stagingRepository.managed", String.valueOf(createdStagingRepositoryId != null));

        final File stagingPropertiesFile = new File(getStagingDirectory(), "stagingRepository.properties");
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(stagingPropertiesFile);
            stagingProperties.store(fout, "Generated by nexus-maven-plugin");
            fout.flush();
        } catch (IOException e) {
            throw new ArtifactDeploymentException(
                    "Error saving staging repository properties to file " + stagingPropertiesFile, e);
        } finally {
            IOUtil.close(fout);
        }
    }
}