Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * The MIT License
   *
   * Copyright (c) 2010, Manufacture Française des Pneumatiques Michelin, Romain Seguy,
   *                     Amadeus SAS, Vincent Latombe
   * Copyright (c) 2007-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt,
   *                          Henrik Lynggaard, Peter Liljenberg, Andrew Bayer
   *
   * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
  * in the Software without restriction, including without limitation the rights
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  * copies of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be included in
  * all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
 
 package com.michelin.cio.hudson.plugins.clearcaseucmbaseline;
 
 import hudson.Util;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
This class represents the actual hudson.model.ParameterValue for the ClearCaseUcmBaselineParameterDefinition parameter.

This value holds the following information:

  • The ClearCase UCM PVOB name (which is actually defined at config-time — cf. ClearCaseUcmBaselineParameterDefinition);
  • The ClearCase UCM component name (which is actually defined at config-time — cf. ClearCaseUcmBaselineParameterDefinition);
  • The ClearCase UCM promotion level (which is actually defined at config-time — cf. ClearCaseUcmBaselineParameterDefinition);
  • The ClearCase UCM view to create name (which is actually defined at config-time — cf. ClearCaseUcmBaselineParameterDefinition);
  • The ClearCase UCM baseline (this is the only one information which is asked at build-time)
  • Author(s):
    Romain Seguy (http://openromain.blogspot.com)
     
     
         // TODO move the attributes of this class and of ClearCaseUcmBaselineParameterDefinition
         // to a single dedicated class to avoid having too much duplicated code
         @Exported(visibility=3) private String baseline;        // this att is set by the user once the build takes place
         @Exported(visibility=3) private String component;       // this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private boolean excludeElementCheckedout// this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private boolean forceRmview;    // this att can be overriden by the user but default value
                                                                 // comes from ClearCaseUcmBaselineParameterDefinition
         private String mkviewOptionalParam;                     // this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private String promotionLevel;  // this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private String pvob;            // this att comes from ClearCaseUcmBaselineParameterDefinition
         private List<Stringrestrictions;                      // this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private boolean snapshotView;   // this att comes from ClearCaseUcmBaselineParameterDefinition
         private String stream;                                  // this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private boolean useUpdate;      // this att comes from ClearCaseUcmBaselineParameterDefinition
         @Exported(visibility=3) private String viewName;        // this att comes from ClearCaseUcmBaselineParameterDefinition
        private StringBuffer fatalErrorMessage = new StringBuffer();
        // I have to have two constructors: If I use only one (the most complete one),
        // I get an exception in ClearCaseUcmBaselineParameterDefinition.createValue(StaplerRequest, JSONObject)
        // while invoking req.bindJSON()
        // Is it because of the two booleans? No time to investigate, sorry.
        public ClearCaseUcmBaselineParameterValue(String nameString baselineboolean forceRmview) {
            this(namenullnullnullnullnullnullbaselinefalseforceRmviewfalsefalse);
        }
                String nameString pvobString componentString promotionLevel,
                String streamString viewNameString mkviewOptionalParamString baseline,
                boolean useUpdateboolean forceRmviewboolean snapshotView,
                boolean excludeElementCheckedout) {
            super(name);
            this. = ClearCaseUcmBaselineUtils.prefixWithSeparator(pvob);
            this. = component;
            this. = promotionLevel;
            this. = stream;
            this. = viewName;
            this. = mkviewOptionalParam;
            this. = baseline;
            this. = useUpdate;
            this. = forceRmview;
            this. = snapshotView;
            if(this.) {
                // the "element * CHECKEDOUT" rule is mandatory for snapshot views
                this. = true;
            }
            else {
                this. = excludeElementCheckedout;
            }
        }

        
    Returns the hudson.tasks.BuildWrapper (defined as an inner class) which does the "checkout" from the ClearCase UCM baseline selected by the user.

    If a ClearCaseUcmBaselineParameterDefinition is added for the build but the SCM is not ClearCaseUcmBaselineSCM, then the hudson.tasks.BuildWrapper which is returned will make the build fail.

        @Override
        public BuildWrapper createBuildWrapper(AbstractBuild<?, ?> build) {
            // let's ensure that a baseline has been really provided
            if( == null || .length() == 0) {
                .append("The value '").append().append("' is not a valid ClearCase UCM baseline.");
            }
            // HUDSON-5877: let's ensure the job has no publishers/notifiers coming
            // from the ClearCase plugin
            DescribableList<PublisherDescriptor<Publisher>> publishersList = build.getProject().getPublishersList();
            for(Publisher publisher : publishersList) {
                if(publisher instanceof UcmMakeBaseline || publisher instanceof UcmMakeBaselineComposite) {
                    if(.length() > 0) {
                        .append('\n');
                    }
                    .append("This job is set up to use a '").append(publisher.getDescriptor().getDisplayName()).append(
                            "' publisher which is not compatible with the ClearCase UCM baseline SCM mode. Please remove this publisher.");
                }
            }
            if(.length() > 0) {
                return new BuildWrapper() {
                    
    This method just makes the build fail for various reasons.
                    @Override
                    public Environment setUp(AbstractBuild buildLauncher launcherBuildListener listenerthrows IOExceptionInterruptedException {
                        listener.fatalError(.toString());
                        return null;
                    }
                };
            }
            if(build.getProject().getScm() instanceof ClearCaseUcmBaselineSCM) {
                // the job is apparently set-up in a clean way, the build can take place
                return new BuildWrapper() {
                    private ClearToolLauncher createClearToolLauncher(TaskListener listenerFilePath workspaceLauncher launcher) {
                        return new HudsonClearToolLauncher(
                                PluginImpl.getDescriptor().getCleartoolExe(),
                                Hudson.getInstance().getDescriptor(ClearCaseUcmBaselineSCM.class).getDisplayName(),
                                listener,
                                workspace,
                                launcher);
                    }

                    
                    private String generateNormalizedViewName(VariableResolver variableResolverString viewName) {
                        String normalizedViewName = Util.replaceMacro(viewNamevariableResolver);
                        normalizedViewName = normalizedViewName.replaceAll("[\\s\\\\\\/:\\?\\*\\|]+""_");
                        return normalizedViewName;
                    }

                    
    This method is the one which actually does the ClearCase stuff (creating the view, setting the config spec, downloading the view, etc.).

    This method is invoked when the user clicks on the 'Build' button appearing on the parameters page.

                    @Override
                    public Environment setUp(AbstractBuild buildfinal Launcher launcherBuildListener listenerthrows IOExceptionInterruptedException {
                        // we use our own variable resolver to have the support for
                        // the CLEARCASE_BASELINE env variable (cf. HUDSON-6410)
                        VariableResolver variableResolver = new BuildVariableResolver(buildlauncherlistener);
                        ClearToolLauncher clearToolLauncher = createClearToolLauncher(listenerbuild.getProject().getSomeWorkspace(), launcher);
                        ClearToolUcmBaseline cleartool = new ClearToolUcmBaseline(variableResolverclearToolLauncher);
                         = generateNormalizedViewName(variableResolver);
                        FilePath workspace = build.getProject().getSomeWorkspace();
                        FilePath viewPath = workspace.child();
                        StringBuilder configSpec = new StringBuilder();
                        // --- 0. Has the same baseline been retrieved during last execution? ---
                        boolean lastBuildUsedSameBaseline = false;
                        if( == false) { // we care only if we don't want to remove the existing view
                            ClearCaseUcmBaselineParameterValue lastCcParamValue = null;
                            // tons of loops and ifs to find the ClearCaseUcmBaselineParameterValue of the last build, if any
                            List<Runbuilds = build.getProject().getBuilds();
                            if(builds.size() > 1) {
                                Run latestBuild = builds.get(1); // builds.get(0) is the currently running build
                                List<ParametersActionactions = latestBuild.getActions(ParametersAction.class);
                                if(actions != null) {
                                    for(ParametersAction action : actions) {
                                        List<ParameterValueparameters = action.getParameters();
                                        if(parameters != null) {
                                            for(ParameterValue parameter : parameters) {
                                                if(parameter instanceof ClearCaseUcmBaselineParameterValue) {
                                                    lastCcParamValue = (ClearCaseUcmBaselineParameterValueparameter;
                                                    // there can be only one time this kind of parameter, so let's break
                                                    break;
                                                }
                                            }
                                        }
                                        if(lastCcParamValue != null) {
                                            // there can be only one time this kind of parameter, so let's break here too
                                            break;
                                        }
                                    }
                                }
                            }
                            if(lastCcParamValue != null) {
                                if(.equals(lastCcParamValue.pvob)
                                        && .equals(lastCcParamValue.component)
                                        && .equals(lastCcParamValue.baseline)) {
                                    // the baseline used in the latest build is the same as the newly requested one
                                    lastBuildUsedSameBaseline = true;
                                }
                            }
                        }
                        final String newlineForOS = launcher.isUnix() ? "\n" : "\r\n";
                        // we assume that the slave OS file separator is the same as the server
                        // since we have no way of determining the OS of the Clearcase server
                        final String fileSepForOS = PathUtil.fileSepForOS(launcher.isUnix());
                        if( || !lastBuildUsedSameBaseline || !viewPath.exists()) {
                            // --- 1. We remove the view if it already exists ---
                            if(viewPath.exists()) {
                                if(! || ) {
                                    cleartool.rmview();
                                    // --- 2. We create the view to be loaded ---
                                    cleartool.mkview(null);
                                }
                            } else {
                                cleartool.mkview(null);
                            }
                            // --- 3. We create the configspec ---
                            if(!) {
                                configSpec.append("element * CHECKEDOUT").append(newlineForOS);
                            }
                            Set<StringloadRules = new HashSet<String>(); // we use a Set to avoid duplicate load rules (cf. HUDSON-6398)
                            // cleartool lsbl -fmt "%[depends_on_closure]p" <baseline>@<pvob>
                            String[] dependentBaselines = cleartool.getDependentBaselines();
                            // we add the selected baseline at the beginning of the dependentBaselines
                            // array so that the "element" and "load" sections of the config spec are
                            // generated for this baseline
                            dependentBaselines = (String[]) ArrayUtils.add(dependentBaselines, 0,  + '@' + );
                            for(String dependentBaselineSelectordependentBaselines) {
                                int indexOfSeparator = dependentBaselineSelector.indexOf('@');
                                if(indexOfSeparator == -1) {
                                    if(.isLoggable(.)) {
                                        .log(."Ignoring dependent baseline '{0}{1}"new Object[]{dependentBaselineSelector'\''});
                                    }
                                    continue;
                                }
                                String dependentBaseline = dependentBaselineSelector.substring(0, indexOfSeparator);
                                String component = cleartool.getComponentFromBaseline(dependentBaseline);
                                String componentRootDir = cleartool.getComponentRootDir(component);
                                // some components may be rootless: they must simply be skipped (cf. HUDSON-6398)
                                if(StringUtils.isBlank(componentRootDir)) {
                                    continue;
                                }
                                // example of generated config spec "element":
                                // element /xxx/spd_comp/... spd_comp_v1.x_20100402100000 -nocheckout
                                configSpec.append("element \"").append(componentRootDir).append(fileSepForOS).append("...\" ").append(dependentBaseline).append(" -nocheckout").append(newlineForOS);
                                // is any download restriction defined?
                                if( != null && .size() > 0) {
                                    for(String restriction) {
                                        // the comparison must not take into account path separators,
                                        // so let's unify them to / for that purpose
                                        String restrictionForComparison = restriction.replace('\\''/');
                                        String componentRootDirForComparison = componentRootDir.replace('\\''/');
                                        if(restrictionForComparison.startsWith(componentRootDirForComparison)) {
                                            // example of generated config spec "load":
                                            // load /xxx/spd_comp/src
                                            loadRules.add("load " + restriction);
                                        }
                                    }
                                }
                                else {
                                    loadRules.add("load " + componentRootDir);
                                }
                            }
                            configSpec.append("element * /main/0 -ucm -nocheckout").append(newlineForOS);
                            for(String loadRuleloadRules) {
                                configSpec.append(loadRule).append(newlineForOS);
                            }
                            listener.getLogger().println("The view will be created based on the following config spec:");
                            listener.getLogger().println("--- config spec start ---");
                            listener.getLogger().print(configSpec.toString());
                            listener.getLogger().println("---  config spec end  ---");
                            // --- 4. We actually load the view based on the configspec ---
                            // cleartool setcs <configspec>
                            cleartool.setcs(configSpec.toString());
                        }
                        else {
                            listener.getLogger().println("The requested ClearCase UCM baseline is the same as previous build: Reusing previously loaded view");
                        }
                        // --- 5. Create the environment variables ---
                        return new Environment() {
                            @Override
                            public void buildEnvVars(Map<StringStringenv) {
                                env.put(.,
                                        );
                                env.put(.,
                                        );
                                env.put(.,
                                        env.get("WORKSPACE") + fileSepForOS + );
                            }
                        };
                    }
                };
            }
            else {
                return new BuildWrapper() {
                    
    This method makes the build fail when a ClearCaseUcmBaselineParameterDefinition parameter is defined for the job, but the SCM is not an instance of ClearCaseUcmBaselineSCM.
                    @Override
                    public Environment setUp(AbstractBuild buildLauncher launcherBuildListener listenerthrows IOExceptionInterruptedException {
                        String ccUcmBaselineSCMDisplayName = Hudson.getInstance().getDescriptor(ClearCaseUcmBaselineSCM.class).getDisplayName();
                        listener.fatalError(
                                "This job is not set up to use a '"
                                + ccUcmBaselineSCMDisplayName
                                + "' SCM while it has a '"
                                + Hudson.getInstance().getDescriptor(ClearCaseUcmBaselineParameterDefinition.class).getDisplayName()
                                + "' parameter: Either remove the parameter or set the SCM to be '"
                                + ccUcmBaselineSCMDisplayName
                                + "'; In the meantime: Aborting!");
                        return null;
                    } 
                };
            }
        }
        public String getBaseline() {
            return ;
        }
        public void setBaseline(String baseline) {
            this. = baseline;
        }
        public String getComponent() {
            return ;
        }
        public void setComponent(String component) {
            this. = component;
        }
        public boolean getExcludeElementCheckedout() {
            return ;
        }
        public void setExcludeElementCheckedout(boolean excludeElementCheckedout) {
            this. = excludeElementCheckedout;
        }
        public boolean getForceRmview() {
            return ;
        }
        public void setForceRmview(boolean forceRmview) {
            this. = forceRmview;
        }
        public String getMkviewOptionalParam() {
            return ;
        }
        public void setMkviewOptionalParam(String mkviewOptionalParam) {
            this. = mkviewOptionalParam;
        }
        public String getPromotionLevel() {
            return ;
        }
        public void setPromotionLevel(String promotionLevel) {
            this. = promotionLevel;
        }
        public String getPvob() {
            return ;
        }
        public void setPvob(String pvob) {
            this. = pvob;
        }
        public void setRestrictions(List<Stringrestrictions) {
            this. = restrictions;
        }
        public boolean getSnapshotView() {
            return ;
        }
        public void setSnapshotView(boolean snapshotView) {
            this. = snapshotView;
        }
        public String getStream() {
            return ;
        }
        public void setStream(String stream) {
            this. = stream;
        }
        public boolean getUseUpdate() {
            return ;
        }
        public void setUseUpdate(boolean useUpdate) {
            this. = useUpdate;
        }
        public String getViewName() {
            return ;
        }
        public void setViewName(String viewName) {
            this. = viewName;
        }
        private final static Logger LOGGER = Logger.getLogger(ClearCaseUcmBaselineParameterValue.class.getName());
    New to GrepCode? Check out our FAQ X