Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package hudson.plugins.collabnet.pblupload;
  
  import hudson.Extension;
  import hudson.FilePath;
  import hudson.Launcher;
 
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
 
 
 import  com.collabnet.cubit.api.CubitConnector;

The PblUploader is used to upload files to the Project Build Library (Pbl) of a Lab Management manager node.
 
 public class PblUploader extends Notifier implements java.io.Serializable {
     private static final String LEFT_NAV_DISPLAY_MESSAGE = "Download from CollabNet Project Build Library";
     private static final String IMAGE_URL = "/plugin/collabnet/images/48x48/";   
     private static final long serialVersionUID = 1L;
     private static String API_URL = "cubit_api";
     private static String API_VERSION = "1";
     private static String PBL_UPLOAD_URL = "pbl_upload";
     private String hostUrl;
     private String user;
     private String key;
     private String project;
     private String pubOrPriv = "priv";
     private String[] file_patterns;
     private String removePrefixRegex;
     private String path;
     private boolean preserveLocal = false;
     private boolean force = false;
     private String comment;
     private String description;
 
     // listener is used for logging and will only be
     // set at the beginning of perform.
     private transient BuildListener listener = null;
    
    
Constructs a new PblUploader instance.

Parameters:
hostUrl for the Cubit host.
user to login as.
key to login with.
project to upload files to
pubOrPriv whether these files should be in the pub (public) or priv (private) directory.
file_patterns matching local files that should be uploaded.
path one the Cubit host where the files will be uploaded.
preserveLocal if true, local directory structure will be copied to the server.
force if true, the files will be uploaded, even if they will overwrite existing files.
comment about the upload.
description of the files.
 
     public PblUploader(String hostUrlString userString keyString project,
                        String pubOrPrivString[] file_patternsString path
                        boolean preserveLocalboolean forceString comment
                        String descriptionString removePrefixRegex) {
         this. = hostUrl;
         this. = user;
         // our sig generator depends on the letters in our hex
         // being lower case
         this. = key.trim().toLowerCase();
         this. = project;
         this. = pubOrPriv;
         this. = file_patterns;
         this. = path;
         this. = preserveLocal;
        this. = force;
        this. = comment;
        this. = description;
        this. = removePrefixRegex;
    }

    

Returns:
the Cubit host's URL.
    public String getHostUrl() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }

    

Returns:
the user to login as.
    public String getUser() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }
    private String returnValueOrEmptyString(String input){
    	if (input != null) {
            return input;
        } else {
            return "";
        }	
    }
    
    
    

Returns:
the key to login with.
    public String getKey() {
      return returnValueOrEmptyString(this.);
    }

    

Returns:
the project to upload files to.
    public String getProject() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }

    

Returns:
"pub" if the files should be uploaded as public, "priv" if the files should be uploaded as private.
    public String getPubOrPriv() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }

    

Returns:
the ant-style file patterns to match against the local workspace.
    public String[] getFilePatterns() {
        if (this. != null) {
            return this.;
        } else {
            return new String[0];
        }
    }

    

Returns:
the path to upload files to on the Cubit host.
    public String getPath() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }

    

Returns:
whether or not local directory structure should be preserved.
    public boolean getPreserveLocal() {
        return this.;
    }

    

Returns:
whether or not the upload should continue if matching files are present.
    public boolean getForce() {
        return this.;
    }

    

Returns:
the comment.
    public String getComment() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }

    

Returns:
the description of the files.
    public String getDescription() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }

    

Returns:
the description of the files.
    public String getRemovePrefixRegex() {
        if (this. != null) {
            return this.;
        } else {
            return "";
        }
    }
    
    
setting the listener allows logging to work

Parameters:
listener to use for logging events.
    private void setupLogging(BuildListener listener) {
        this. = listener;
    }

    
Logging will only work once the listener is set. Otherwise, it will fail (silently).

Parameters:
message to log.
    private void log(String message) {
        if (this. != null) {
            this..getLogger().println(message);
        }
    }
    @Override
        return .;
    }

    
Upload the files to the PBL. This is the hudson builds entry point into this plugin

Parameters:
build the current Hudson build.
launcher unused.
listener for events.
Returns:
true if uploading files succeeded.
Throws:
InterruptedException
IOException
    @Override
    public boolean perform(AbstractBuild<?, ?> buildLauncher launcher,
            BuildListener listenerthrows java.lang.InterruptedException,
            IOException {
        boolean success = true;
        this.setupLogging(listener);
        this.log("");
        if (build.getResult() == .) {
            this.log("Not attempting to upload files to Project Build " +
                     "Library because the build has failed.");
            return true;
        }
        this.log("Uploading files to Project Build Library");
        this.log(this.getRemoteURL(build));
        success = this.uploadFiles(build);
        
        // add result to build page
        build.
            addAction(new 
                      PblUploadResultAction(
                                             + "cubit-icon.gif"
                                            "console"
                                            addTrailSlash(this.
                                                          getRemoteURL(build)),
                                            success));
        
        if (success == false) {
            // set the build result to the worse of the current result
            // and UNSTABLE
            build.setResult(build.getResult().combine(.));
        }
        return success;
    }

    
Processes the configured list of file patterns to upload to the pbl. All patterns are processed by the method getFilePatterns, and any empty strings (which can result after) processing are ignored.

Parameters:
build the current hudson build
Returns:
List of file patterns, after being interpreted with empty strings removed.
    private List<StringgetProcessedFilePatterns(AbstractBuild<?, ?> build)
            throws IOExceptionInterruptedException {
        List<Stringoutput = new ArrayList<String>();
        for (String uninterp_fp : this.getFilePatterns()) {
            String file_pattern = "";
            try {
                file_pattern = getInterpreted(builduninterp_fp);
                if (!file_pattern.equals("")){
                    output.add(file_pattern);
                }
            } catch (IllegalArgumentException e) {
                this.log("File pattern " + uninterp_fp + " contained a bad "
                         + "env var.  Skipping.");
            }
        }
        return output;
    }
    
    
This methods is calculates the success or fail of the pbl upload plugin and logs the state to Hudson build log. Success occurs if any files are successfully uploaded.

Parameters:
num_files Total number of files processed during upload
failures Total number of files that failed to upload
Returns:
true if some files uploaded successfully
    private boolean determineAndLogFinalState(int num_filesint failures){
        num_files = num_files > 0 ? num_files: 0;
        failures = failures > 0 ? failures: 0;
        if (num_files == 0) {
            this.log("Could not find any matching files to upload.  "
                     + "Please check your file patterns.");
            return false;
        } else if (num_files == failures) {
            this.log("No files successfully uploaded.  "
                     + "You may want to check your " +
                     "configuration or the status of " +
                     "the Lab Management Manager.");
            return false;
        } else if (failures == 0) {
            this.log(num_files + " files successfully uploaded!");
            return true;
        } else {
            this.log("Attempted to upload " + num_files + " files.");
            this.log(failures + " file uploads failed.");
            this.log((num_files - failures) + " file uploads succeeded.");
            return true;
        }
    }
    
    
Upload the files.

Parameters:
build the current Hudson build.
Returns:
true, if successful, false otherwise.
Throws:
IOException
InterruptedException
    private boolean uploadFiles(AbstractBuild<?, ?> build) {
        try {
            FilePath workspace = build.getWorkspace();
            int num_files = 0;
            int failures = 0;
            this.log("");
            for (String file_pattern : getProcessedFilePatterns(build)) {
                this.log("Upload files matching " + file_pattern + ":");
                for (FilePath pathOfFileToUpload : workspace.list(file_pattern)) {
                    num_files++;
                    Map<StringStringargs = this.setupArgs(build
                                                              pathOfFileToUpload
                                                              workspace);
                    if (!this.pblUpload(argspathOfFileToUploadworkspace)) {
                        failures++;
                    }
                }
                this.log("");
            }
            return determineAndLogFinalState(num_filesfailures);
        } catch (Exception e) {
            this.log("CRITICAL ERROR: Upload of files failed due to: " 
                     + e.getMessage());
            return false;
        }      
    }

    

Returns:
the local path to the uploaded file.
    private String getLocalFilePath(FilePath workspace
                                    FilePath uploadFilePath) {
        String path = this.getRelativePath(workspaceuploadFilePath) +
            uploadFilePath.getName();
        if (path.startsWith("/")) {
            path = path.replaceFirst("/""");
        }
        return path;
    }

    

Returns:
the URL for where our upload will end up.
    private String getRemoteURL(AbstractBuild<?, ?> build)
            throws IOExceptionInterruptedException {
        return addTrailSlash(getHostUrl())+"pbl/" + addTrailSlash(this.getProject()) 
            + this.getPubOrPriv() + "/"
            + this.getInterpreted(buildthis.getPath());           
    }

    

Parameters:
str with or without slash
Returns:
string with trailing slash.
    private static String addTrailSlash(String str) {
        if (str.endsWith("/")) {
            return str;
        } else {
            return str + "/";
        }
    }

    
Figure out what the full path of the uploaded file should be.

Parameters:
build the current Hudson build.
workspace
uploadFilePath
Returns:
a string with the interpreted path plus possibly the local directory structure.
    private String createUploadPath(AbstractBuild<?, ?> build
                                    FilePath workspaceFilePath uploadFilePath)
                                    throws IOExceptionInterruptedException {
        String fileDestinationPath = this.getInterpreted(buildthis.getPath());
        if (this.getPreserveLocal()){
            String localPath = this.getRelativePath(workspaceuploadFilePath);
            if (this. != null && 
                !"".equals(this.)) {
                if (localPath.split().length > 0 &&
                    // makes sure the regex is a prefix
                    localPath.split()[0].equals("")){ 
                    localPath = localPath.replaceFirst("");
                }
                if (localPath.matches()) {
                    // if the entire localPath matches, it's removed entirely
                    localPath = "";
                }
            }
            fileDestinationPath = addTrailSlash(fileDestinationPath) + 
                localPath;
        }
        return fileDestinationPath;
    }

    
Translates a string that may contain build vars like ${BUILD_VAR} to a string with those vars interpreted.

Parameters:
build the Hudson build.
str the string to be interpreted.
Returns:
the interpreted string.
Throws:
IllegalArgumentException if the env var is not found.
    private String getInterpreted(AbstractBuild<?, ?> buildString str)
            throws IOExceptionInterruptedException {
        Map<StringStringenvVars = null;
        if (Hudson.getInstance().getPlugin("promoted-builds") != null
            && build.getClass().equals(Promotion.class)) {
            // if this is a promoted build, get the env vars from
            // the original build
            Promotion promotion = Promotion.class.cast(build);
            envVars = promotion.getTarget().getEnvironment(.);
        } else {
            envVars = build.getEnvironment(.);
        }
        try {
            //XXX should this use envVars instead of build.getEnv.... ?
            return CommonUtil.getInterpreted(build.getEnvironment(.), str);
        } catch (IllegalArgumentException iae) {
            this.log(iae.getMessage());
            throw iae;
        }
    }

    
Returns the relative directory path between a child and it's ancestor FilePath. For example, if ancestor = /a/b/c/d/ and child = /a/b/c/d/e/f/g.txt this function will return /e/f. If ancestor is not really an ancestor, "" will be returned.

Parameters:
ancestor
child
Returns:
the child's directory, relative to the ancestor's.
    private String getRelativePath(FilePath ancestorFilePath child) {
        try {
            String ancestor_str = ancestor.toURI().toString();
            String child_str = child.getParent().toURI().toString();
            if (child_str.startsWith(ancestor_str)) {
                return child_str.replaceFirst(ancestor_str"");
            }
        } catch (InterruptedException e){
            //TODO: perhaps log this.
        } catch (IOException e){
            //TODO: perhaps log this.
        } 
        return "";
    }

    
Setup of the args needed for uploading files.

Parameters:
build the current Hudson build.
uploadFilePath
workspace
Returns:
a key, value map of the args.
Throws:
IOException
InterruptedException
    private Map<StringStringsetupArgs(AbstractBuild<?, ?> build,
                                          FilePath uploadFilePath,
                                          FilePath workspace
        throws IOExceptionInterruptedException {
        Map<StringStringargs = new HashMap<StringString>();
        String md5sum = uploadFilePath.digest();
        String path;
        String description;
        String comment;
        try {
            path = this.createUploadPath(buildworkspaceuploadFilePath);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Setting up args failed due to"
                                               + " bad path: " 
                                               + e.getMessage());
        }
        try {
            description = this.getInterpreted(buildthis.getDescription());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Setting up args failed due to"
                                               + " bad description: " 
                                               + e.getMessage());
        }
        try {
            comment = this.getInterpreted(buildthis.getComment());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Setting up args failed due to"
                                               + " bad comment: " 
                                               + e.getMessage());
        }
        args.put("md5sum"md5sum);
        args.put("path"path);
        args.put("proj"this.getProject());
        args.put("type"this.getPubOrPriv());
        args.put("userid"this.getUser());
        if (this.getForce()){
            /* The value is irrelevant, the presence of the parameter is 
             * all the server needs to force the upload 
             */
            args.put("force","TRUE");
        } 
        args.put("comment"comment);
        args.put("desc"description);
        return args;
    }
    
    private void logPblCallResults(CubitConnector.ResponseCodeAndBody response,
                                   Map <StringStringargs,
                                   FilePath uploadFilePath,
                                   FilePath workspace){
        String localFilePath = this.getLocalFilePath(workspace,
                                                     uploadFilePath);
        String remoteURL = addTrailSlash(addTrailSlash(getHostUrl()) + "pbl/" 
                                         + addTrailSlash(args.get("proj")) 
                                         + args.get("type") + "/"
                                         + args.get("path"
                                        ) + uploadFilePath.getName();
        String resultStr = "Upload for file " + localFilePath
                           + " -> " + remoteURL;
        if (response.getStatus() == 200) {
           this.log(resultStr + ": OK");
        } 
        else {
            String[] lines = response.getBody().split("\\n");
            this.log("Upload for file " + uploadFilePath.getName() + 
            " failed: ");
            for (int i = 0; i < lines.lengthi++) {
                this.log(lines[i]);
            }
            this.log(resultStr + ": FAILED");
        }
    }
    
    
    
Do the upload.

Parameters:
args to send to the Lab Management server.
uploadFilePath to the uploading file.
Returns:
true, if successful.
Throws:
IOException
InterruptedException
    private boolean pblUpload(final Map<StringStringargs
                              FilePath uploadFilePath,
                              FilePath workspace
        throws IOExceptionInterruptedException {
        CubitConnector.ResponseCodeAndBody result = uploadFilePath.
            act(new FileCallable<CubitConnector.ResponseCodeAndBody>() {
			private static final long serialVersionUID = 1L;
                        @Override
			public CubitConnector.ResponseCodeAndBody invoke(File fileVirtualChannel channel
            throws FileNotFoundExceptionIOException
            {
		        final CubitConnector cubitConnector = new CubitConnector(getHostUrl(),
		                                                                 getUser(),
		                                                                 getKey());
 			    return cubitConnector.callCubit(
                                                args
                                                file,
                                                true);
            }
        });
        logPblCallResults(resultargsuploadFilePathworkspace);
        return(result.getStatus() == 200);
    }

    
PBLUploader does not need to wait til the build is finalized.
    @Override
    public boolean needsToRunAfterFinalized() {
        return false;
    }

    
Descriptor for PblUploader. Used as a singleton. The class is marked as public so that it can be accessed from views.
    @Extension
    public static final class DescriptorImpl 
        extends BuildStepDescriptor<Publisher> {
        private static int unique = 0;
        public DescriptorImpl() {
            super(PblUploader.class);
        }

        

Returns:
a unique integer, used to identify an instance of the PBLUploader plugin on a page.
        public synchronized int getUniqueId() {
            int return_value = ;
            ++;
            if ( >= .) {
                 = 0;
            }
            return return_value;
        }

        

Returns:
human-readable name used in the configuration screen.
        @Override
        public String getDisplayName() {
            return "Lab Management Project Build Library (PBL) Uploader";
        }

        

Returns:
the path to the help files.
        public String getHelpUrl() {
            return "/plugin/collabnet/pblupload/";
        }

        

Returns:
url for the generic help-file for this plug-in.
        @Override
        public String getHelpFile() {
            return getHelpUrl() + "help-projectConfig.html";
        }

        
The PblUploader can be used as a post-promotion task.

Parameters:
jobType
Returns:
true
        @Override
        @SuppressWarnings("unchecked")
        public boolean isApplicable(java.lang.Class<? extends AbstractProjectjobType) {
            return true;
        } 

        
Creates a new instance of PblUploader from a submitted form.

Parameters:
req config page parameters.
formData data specific to this section, in json form.
Returns:
new PblUploader instance.
Throws:
FormException
        @Override
        public PblUploader newInstance(StaplerRequest req
                                       JSONObject formData
        throws FormException {
            Object fileData = formData.get("files");
            JSONObject[] jpats;
            if (fileData instanceof JSONArray) {
                JSONArray patData = (JSONArrayfileData;
                jpats = (JSONObject []) JSONArray.toArray(patData
                                                          JSONObject.class);
            } else if (fileData instanceof JSONObject) {
                jpats = new JSONObject[1];
                jpats[0] = (JSONObjectfileData;
            } else {
                jpats = new JSONObject[0];
            }
            String[] patterns = new String[jpats.length];
            for (int i = 0; i < jpats.lengthi++) {
                patterns[i] = (Stringjpats[i].get("file");
            }
            
            return new PblUploader((String)formData.get("host_url"), 
                                   (String)formData.get("user"), 
                                   (String)formData.get("key"),
                                   (String)formData.get("project"),
                                   (String)formData.get("pub_or_priv"),
                                   patterns,
                                   (String)formData.get("path"),
                                   formData.get("preserve") != null,
                                   CommonUtil.getBoolean("force"formData),
                                   (String)formData.get("comment"),
                                   (String)formData.get("description"),
                                   formData.get("preserve") != null?
                                       (String)((JSONObject)formData.
                                           get("preserve")).
                                           get("remove_prefix_regex"):
                                       ""
                                   );
        }
        
        
Form validation for the host_url

Parameters:
value url
        public FormValidation doHostUrlCheck(@QueryParameter String value) {
            return CNFormFieldValidator.hostUrlCheck(value);
        }

        
Form validation for the user and project

Parameters:
value
name of field
        public FormValidation doRequiredCheck(
                @QueryParameter String value, @QueryParameter String name) {
            return CNFormFieldValidator.requiredCheck(valuename);
        }

        
Form validation for the API key.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
        public FormValidation doKeyCheck(StaplerRequest req) {
            return CNFormFieldValidator.cubitKeyCheck(req);
        }

        
Form validation for the path.

Parameters:
value
name of field
                @QueryParameter String value, @QueryParameter String name) {
            return CNFormFieldValidator.requiredInterpretedCheck(valuename);
        }

        
        
Form validation for the path.

Parameters:
value
        public FormValidation doRegexPrefixCheck(@QueryParameter String value) {
            return CNFormFieldValidator.regexCheck(value);
        }
        
        
Form validation for the comment and description.

Parameters:
value
name of field
                @QueryParameter String value, @QueryParameter String name) {
            return CNFormFieldValidator.unrequiredInterpretedCheck(valuename);
        }
    }
New to GrepCode? Check out our FAQ X