Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 JFrog Ltd.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.jfrog.hudson.release.maven;
 
 import  org.jfrog.build.extractor.maven.transformer.SnapshotNotAllowedException;
 
 import java.util.Map;
A release wrapper for maven projects. Allows performing release steps on maven

Author(s):
Yossi Shaul
 
 public class MavenReleaseWrapper extends BuildWrapper {
     private static final Logger debuggingLogger = Logger.getLogger(MavenReleaseWrapper.class.getName());
 
     private String tagPrefix;
     private String releaseBranchPrefix;
     private String alternativeGoals;
     private String defaultVersioning;
 
     private transient ScmCoordinator scmCoordinator;
 
     public MavenReleaseWrapper(String releaseBranchPrefixString tagPrefixString alternativeGoals,
             String defaultVersioning) {
         this. = releaseBranchPrefix;
         this. = tagPrefix;
         this. = alternativeGoals;
         this. = defaultVersioning;
     }
 
     public String getTagPrefix() {
         return ;
     }
 
     @SuppressWarnings({"UnusedDeclaration"})
     public void setTagPrefix(String tagPrefix) {
         this. = tagPrefix;
     }
 
     public String getReleaseBranchPrefix() {
         return ;
     }
 
     @SuppressWarnings({"UnusedDeclaration"})
     public void setReleaseBranchPrefix(String releaseBranchPrefix) {
         this. = releaseBranchPrefix;
     }
 
     @SuppressWarnings({"UnusedDeclaration"})
     public String getAlternativeGoals() {
         return ;
     }
    @SuppressWarnings({"UnusedDeclaration"})
    public void setAlternativeGoals(String alternativeGoals) {
        this. = alternativeGoals;
    }
    @SuppressWarnings({"UnusedDeclaration"})
    public String getDefaultVersioning() {
        return ;
    }
    @SuppressWarnings({"UnusedDeclaration"})
    public void setDefaultVersioning(String defaultVersioning) {
        this. = defaultVersioning;
    }
    @Override
    public Environment setUp(AbstractBuild buildLauncher launcherBuildListener listener)
            throws IOExceptionInterruptedException {
        final ReleaseAction releaseAction = build.getAction(ReleaseAction.class);
        if (releaseAction == null) {
            // this is a normal non release build, continue with normal environment
            return new Environment() {
            };
        }
        log(listener"Release build triggered");
        final MavenModuleSetBuild mavenBuild = (MavenModuleSetBuildbuild;
         = AbstractScmCoordinator.createScmCoordinator(buildlistenerreleaseAction);
        .prepare();
        if (!releaseAction.getVersioning().equals(..)) {
            // change to release version
            String vcsUrl = releaseAction.isCreateVcsTag() && AbstractScmCoordinator.isSvn(build.getProject())
                    ? releaseAction.getTagUrl() : null;
            boolean modified;
            try {
                log(listener"Changing POMs to release version");
                modified = changeVersions(mavenBuildreleaseActiontruevcsUrl);
            } catch (SnapshotNotAllowedException e) {
                log(listener"ERROR: " + e.getMessage());
                // abort the build
                return null;
            }
            .afterReleaseVersionChange(modified);
        }
        final MavenModuleSet mavenModuleSet = mavenBuild.getProject();
        final String originalGoals = mavenModuleSet.getGoals();
        if (!StringUtils.isBlank()) {
            .fine("Using alternative goals and settings: " + );
            mavenModuleSet.setGoals();
        }
        return new Environment() {
            @Override
            public boolean tearDown(AbstractBuild buildBuildListener listener)
                    throws IOExceptionInterruptedException {
                // if we used alternative goals set back the original
                if (!StringUtils.isBlank()) {
                    mavenModuleSet.setGoals(originalGoals);
                }
                if (build.getResult().isWorseThan(.)) {
                    // revert will happen by the listener
                    return true;
                }
                try {
                    .afterSuccessfulReleaseVersionBuild();
                    if (!releaseAction.getVersioning().equals(..)) {
                        .beforeDevelopmentVersionChange();
                        // change poms versions to next development version
                        String scmUrl = releaseAction.isCreateVcsTag() &&
                                AbstractScmCoordinator.isSvn(build.getProject())
                                ? .getRemoteUrlForPom() : null;
                        log(listener"Changing POMs to next development version");
                        boolean modified = changeVersions(mavenBuildreleaseActionfalsescmUrl);
                        .afterDevelopmentVersionChange(modified);
                    }
                } catch (Exception e) {
                    listener.getLogger().println("Failure in post build SCM action: " + e.getMessage());
                    .log(."Failure in post build SCM action: "e);
                    return false;
                }
                return true;
            }
        };
    }
    private boolean changeVersions(MavenModuleSetBuild mavenBuildReleaseAction releaseboolean releaseVersion,
            String scmUrlthrows IOExceptionInterruptedException {
        FilePath moduleRoot = mavenBuild.getModuleRoot();
        // get the active modules only
        Collection<MavenModulemodules = mavenBuild.getProject().getDisabledModules(false);
        Map<ModuleNameStringmodulesByName = Maps.newHashMap();
        for (MavenModule module : modules) {
            String version = releaseVersion ? release.getReleaseVersionFor(module.getModuleName()) :
                    release.getNextVersionFor(module.getModuleName());
            modulesByName.put(module.getModuleName(), version);
        }
        boolean modified = false;
        for (MavenModule mavenModule : modules) {
            String relativePath = mavenModule.getRelativePath();
            String pomRelativePath = StringUtils.isBlank(relativePath) ? "pom.xml" : relativePath + "/pom.xml";
            FilePath pomPath = new FilePath(moduleRootpomRelativePath);
            .fine("Changing version of pom: " + pomPath);
            .edit(pomPath);
            modified |= pomPath.act(
                    new PomTransformer(mavenModule.getModuleName(), modulesByNamescmUrlreleaseVersion));
        }
        return modified;
    }
    private void log(BuildListener listenerString message) {
        listener.getLogger().println("[RELEASE] " + message);
    }
    @Override
    public Collection<? extends ActiongetProjectActions(AbstractProject job) {
        return Arrays.asList(new MavenReleaseAction((MavenModuleSetjob));
    }
    @Override
    public DescriptorImpl getDescriptor() {
        return (DescriptorImplsuper.getDescriptor();
    }
    @Extension
    public static final class DescriptorImpl extends BuildWrapperDescriptor {
        public DescriptorImpl() {
            super(MavenReleaseWrapper.class);
            load();
        }

        
This wrapper applied to maven projects with subversion only.

Parameters:
item The current project
Returns:
True for maven projects with subversion as the scm
        @Override
        public boolean isApplicable(AbstractProject<?, ?> item) {
            return (item instanceof MavenModuleSet)/* && (item.getScm() instanceof SubversionSCM)*/;
        }

        

Returns:
The message to be displayed next to the checkbox in the job configuration.
        @Override
        public String getDisplayName() {
            return "Enable Artifactory release management";
        }

        

Returns:
Model with the release actions allowed. Used to set the defaultVersioning.
        @SuppressWarnings({"UnusedDeclaration"})
        public ListBoxModel doFillDefaultVersioningItems() {
            ListBoxModel model = new ListBoxModel();
            for (ReleaseAction.VERSIONING versioning : ReleaseAction.VERSIONING.values()) {
                model.add(versioning.getDisplayMessage(), versioning.toString());
            }
            return model;
        }
    }

    
This run listener handles the job completed event to cleanup svn tags and working copy in case of build failure.
    @Extension
    public static final class ReleaseRunListener extends RunListener<AbstractBuild> {
        
Completed event is sent after the build and publishers execution. The build result in this stage is final and cannot be modified. So this is a good place to revert working copy and tag if the build failed.
        @Override
        public void onCompleted(AbstractBuild runTaskListener listener) {
            if (!(run instanceof MavenModuleSetBuild)) {
                return;
            }
            ReleaseAction releaseAction = run.getAction(ReleaseAction.class);
            if (releaseAction == null) {
                return;
            }
            // signal completion to the scm coordinator
            MavenModuleSet project = ((MavenModuleSetBuildrun).getProject();
            ArtifactoryRedeployPublisher redeployPublisher =
                    ActionableHelper.getPublisher(projectArtifactoryRedeployPublisher.class);
            if (!redeployPublisher.isAllowPromotionOfNonStagedBuilds()) {
                Result result = run.getResult();
                if (result.isBetterOrEqualTo(.)) {
                    // add a stage action
                    run.addAction(new UnifiedPromoteBuildAction<ArtifactoryRedeployPublisher>(runredeployPublisher));
                }
            }
            MavenReleaseWrapper wrapper = ActionableHelper.getBuildWrapper(projectMavenReleaseWrapper.class);
            try {
                wrapper.scmCoordinator.buildCompleted();
            } catch (Exception e) {
                run.setResult(.);
                listener.error("[RELEASE] Failed on build completion");
                e.printStackTrace(listener.getLogger());
            }
            // remove the release action from the build. the stage action is the point of interaction for successful builds
            run.getActions().remove(releaseAction);
        }
    }
New to GrepCode? Check out our FAQ X