Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package hudson.plugins.collabnet.filerelease;
  
  
  import  com.collabnet.ce.soap50.webservices.frs.FrsFileSoapDO;
  
  import hudson.Launcher;
 
 
 
 import java.io.File;
 import java.util.Map;
 
 
 
Hudson plugin to update files from the Hudson workspace to the CollabNet File Release System.
 
 public class CNFileRelease extends Publisher {
     // listener is used for logging and will only be
     // set at the beginning of perform.
     private transient BuildListener listener = null;
 
     private static final String IMAGE_URL = "/plugin/collabnet/images/48x48/";
     
     // collabNet object
     private transient CollabNetApp cna = null;
 
     // Variables from the form
     private boolean override_auth = true;
     private String url;
     private String username;
     private String password;
     private String project;
     private String rpackage;
     private String release;
     private boolean overwrite;
     private String[] file_patterns;
 
     private transient static TeamForgeShare.TeamForgeShareDescriptor 
         shareDescriptor = null;

    
Creates a new CNFileRelease object.

Parameters:
url for the CollabNet server, i.e. http://forge.collab.net
username used to log into the CollabNet server.
password for the logging-in user.
project where the files will be uploaded. The project contains the package.
package where the files will be uploaded. The package contains the release.
release where the files will be uploaded.
overwrite whether or not to overwrite existing files.
filePatterns Any files in the Hudson workspace that match these ant-style patterns will be uploaded to the CollabNet server.
 
     public CNFileRelease(String urlString usernameString password
                          String projectString rpackageString release
                          boolean overwriteString[] filePatterns
                          boolean override_auth) {
         this. = url;
         this. = username;
         this. = password;
         this. = project;
         this. = rpackage;
         this. = release;
         this. = overwrite;
        this. = filePatterns;
        this. = override_auth;
    }

    
Setting the listener allows logging to work.

Parameters:
listener passed into the perform method.
    private void setupLogging(BuildListener listener) {
        this. = listener;
    }

    
Log a message to the console. Logging will only work once the listener is set. Otherwise, it will fail (silently).

Parameters:
message A string to print to the console.
    private void log(String message) {
        if (this. != null) {
            message = "CollabNet FileRelease: " + message;
            this..getLogger().println(message);
        }
    }
    
    
Convenience method to log RemoteExceptions.

Parameters:
methodName in progress on when this exception occurred.
re The RemoteException that was thrown.
    private void log(String methodNameRemoteException re) {
        this.log(methodName + " failed due to " + re.getClass().getName() + 
                 ": " + re.getMessage());
    }

    

Returns:
whether or not auth is overriden
    public boolean overrideAuth() {
        return this.;
    }

    

Returns:
the url for the CollabNet server.
    public String getCollabNetUrl() {
        if (this.overrideAuth()) {
            return this.;
        } else {
            return getTeamForgeShareDescriptor().getCollabNetUrl();
        }
    }

    

Returns:
the username used for logging in.
    public String getUsername() {
        if (this.overrideAuth()) {
            return this.;            
        } else {
            return getTeamForgeShareDescriptor().getUsername();
        }
    }

    

Returns:
the password used for logging in.
    public String getPassword() {
        if (this.overrideAuth()) {
            return this.;
        } else {
            return getTeamForgeShareDescriptor().getPassword();
        }
    }

    

Returns:
the project where the files are uploaded.
    public String getProject() {
        return this.;
    }

    

Returns:
the package of the release where the files are uploaded.
    public String getPackage() {
        return this.;
    }

    

Returns:
the release where the files are uploaded.
    public String getRelease() {
        return this.;
    }

    

Returns:
whether or not existing files should be overwritten.
    public boolean overwrite() {
        return this.;
    }

    

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

    

Returns:
the TeamForge share descriptor.
        getTeamForgeShareDescriptor() {
        if ( == null) {
             = TeamForgeShare.getTeamForgeShareDescriptor();
        }
        return ;
    }

    

Returns:
the list of all possible projects, given the login data.
    public String[] getProjects() {
        CollabNetApp cna = CNHudsonUtil.getCollabNetApp(this.getCollabNetUrl(),
                                                        this.getUsername(), 
                                                        this.getPassword());
        Collection<Stringprojects = ComboBoxUpdater.ProjectsUpdater
            .getProjectList(cna);
        CNHudsonUtil.logoff(cna);
        return projects.toArray(new String[0]);
    }

    

Returns:
the list of all possible packages, given the login data and the project.
    public String[] getPackages() {
        CollabNetApp cna = CNHudsonUtil.getCollabNetApp(this.getCollabNetUrl(),
                                                        this.getUsername(), 
                                                        this.getPassword());
        String projectId = CNHudsonUtil.getProjectId(cnathis.getProject());
        Collection<Stringpackages = ComboBoxUpdater.PackagesUpdater
            .getPackageList(cnaprojectId);
        CNHudsonUtil.logoff(cna);
        return packages.toArray(new String[0]);
    }

    

Returns:
the list of all possible releases, given the login data, the project and the package.
    public String[] getReleases() {
        CollabNetApp cna = CNHudsonUtil.getCollabNetApp(this.getCollabNetUrl(),
                                                        this.getUsername(), 
                                                        this.getPassword());
        String packageId = this.getPackageId(this.getProjectId());
        Collection<Stringreleases = ComboBoxUpdater.ReleasesUpdater
            .getReleaseList(cnapackageId);
        CNHudsonUtil.logoff(cna);
        return releases.toArray(new String[0]);
    }

    
The function does the work of uploading files for the release.

Parameters:
build current Hudson build.
launcher unused.
listener receives events that happen during a build. We use it for logging.
Returns:
true if successful, false if a critical error occurred.
    public boolean perform(AbstractBuild<?, ?> buildLauncher launcher
                           BuildListener listener) {
        this.setupLogging(listener);
        this. = CNHudsonUtil.getCollabNetApp(this.getCollabNetUrl(), 
                                                this.getUsername(), 
                                                this.getPassword());
        if (this. == null) {
            this.log("Critical Error: login to " + this.getCollabNetUrl() + 
                     " failed.  Setting build status to UNSTABLE (or worse).");
            Result previousBuildStatus = build.getResult();
            build.setResult(previousBuildStatus.combine(.));
            build.addAction(this.createAction(0, null));
            return false;
        }
        String releaseId = this.getReleaseId();
        if (releaseId == null) {
            Result previousBuildStatus = build.getResult();
            build.setResult(previousBuildStatus.combine(.));
            this.logoff();
            build.addAction(this.createAction(0, releaseId));
            return false;
        }
        // now that we have the releaseId, we can do the upload.
        int numUploaded = this.uploadFiles(buildreleaseId);
        build.addAction(this.createAction(numUploadedreleaseId));
        this.logoff();
        return true;
    }

    
Get the ResultAction for this build.

Parameters:
success true if successful, false otherwise.
Returns:
CnfrResultAction.
    public CnfrResultAction createAction(int numUploadedString releaseId) {
        String displaymsg = "Download from CollabNet File Release System";
        return new CnfrResultAction(displaymsg
                                     + "cn-icon.gif"
                                    "console"
                                    this.getFileReleaseUrl(releaseId), 
                                    numUploaded);
    }

    

Parameters:
releaseId
Returns:
a link to the file release or the collabnet url if we don't have a releaseId.
    private String getFileReleaseUrl(String releaseId) {
        String path = null;
        if (releaseId != null) {
            FrsApp fa = new FrsApp(this.);
            try {
                path = fa.getReleasePath(releaseId);                
            } catch (RemoteException re) {
                this.log("get release path"re);
            }
        }
        if (path != null) {
            return this.getCollabNetUrl() + "/sf/frs/do/viewRelease/" + path;
        } else {
            return this.getCollabNetUrl();
        }
    }

    

Parameters:
filePath path to uploaded frs file.
Returns:
url to uploaded frs file.
    private String getFileUrl(String path) {
        return this.getCollabNetUrl() + "/sf/frs/do/downloadFile/" + path;
    }

    
Upload the files which match the file patterns to the given releaseId.

Parameters:
build current Hudson build.
releaseId where the files will be uploaded.
Returns:
the number of files successfully uploaded.
    public int uploadFiles(AbstractBuild<?, ?> build
                            final String releaseId) {
        int numUploaded = 0;
        final FileStorageApp sfsa = new FileStorageApp(this.);
        final FrsApp fa = new FrsApp(this.);
        this.log("Uploading file to project '" + this.getProject() + 
                 "', package '" + this.getPackage() + "', release '" + 
                 this.getRelease() + "' on host '" + this.getCollabNetUrl() + 
                 "' as user '" + this.getUsername() + "'.");
        // upload files
        for (String uninterp_fp : this.getFilePatterns()) {
            String file_pattern = "";
            try {
                file_pattern = getInterpreted(builduninterp_fp); 
            } catch (IllegalArgumentException e) {
                this.log("File pattern " + uninterp_fp + " contained a bad "
                         + "env var.  Skipping.");
                continue;
            }
            if (file_pattern.equals("")) {
                // skip empty fields
                continue;
            }
            this.log("Upload files matching " + file_pattern + ":");
            for (FilePath uploadFilePath : this.getFilePaths(build
                                                             file_pattern)) {
                // check if a file already exists
                String fileId = null;
                try {
                    fileId = fa.findFrsFile(uploadFilePath.getName(), 
                                            releaseId);
                } catch (RemoteException re) {
                    this.log("find file"re);
                }
                if (fileId != null) {
                    if (this.overwrite()) {
                        // delete existing file
                        try {
                            fa.deleteFrsFile(fileId);
                            this.log("Deleted previously uploaded file: " + 
                                     uploadFilePath.getName());
                        } catch (RemoteException re) {
                            this.log("delete file"re);
                        }                    
                    } else {
                        this.log("File " + uploadFilePath.getName() + 
                                 " already exists in the file release " +
                                 "system and overwrite is set to false.  " +
                                 "Skipping.");
                        continue;
                    }
                }
                try {
                    String path = uploadFilePath.
                        act(new FileCallable<String>() {
                            public String invoke(File f
                                                 VirtualChannel channel
                            throws IOExceptionRemoteException {
                                String fileId = sfsa.uploadFile(f);
                                FrsFileSoapDO fileSoap = fa.
                                createFrsFile(releaseId
                                              f.getName(), 
                                              CNFileRelease.getMimeType(f), 
                                              fileId);
                                return fileSoap.getPath();
                            }
                        });
                    this.log("Uploaded file " + uploadFilePath.getName() + 
                             " -> " + this.getFileUrl(path));
                    numUploaded++;
                } catch (RemoteException re) {
                    this.log("upload file"re);
                } catch (IOException ioe) {
                    this.log("Could not upload file due to IOException: " 
                             + ioe.getMessage());
                } catch (InterruptedException ie) {
                    this.log("Could not upload file due to " +
                             "InterruptedException: " + ie.getMessage());
                }
                
            }
        }
        return numUploaded;
    }

    
Return the filepaths in the workspace which match the pattern.

Parameters:
build The hudson build.
pattern An ant-style pattern.
Returns:
an array of FilePaths which match this pattern in the hudson workspace.
    private FilePath[] getFilePaths(AbstractBuild<?, ?> build
                                    String pattern) {
        FilePath workspace = build.getProject().getWorkspace();
        FilePath[] uploadFilePaths = new FilePath[0];
        try {
            uploadFilePaths = workspace.list(pattern);
        } catch (IOException ioe) {
            this.log("Could not list workspace due to IOException: " 
                     + ioe.getMessage());
        } catch (InterruptedException ie) {
            this.log("Could not list workspace due to " +
                     "InterruptedException: " + ie.getMessage());
        }
        return uploadFilePaths;
    }

    
Get the mimetype for the file.

Parameters:
f The file to return the mimetype for.
Returns:
the string representing the mimetype of the file.
    public static String getMimeType(File f) {
        return new MimetypesFileTypeMap().getContentType(f);
    }

    
Log out of the collabnet server. Invalidates the cna object.
    public void logoff() {
        if (this. != null) {
            CNHudsonUtil.logoff();
            this. = null;
        } else {
            this.log("logoff failed. Not logged in!");
        }
    }

    
Get the releaseId from the project/package/release names. Returns null if somewhere along the way one of these IDs cannot be found.

Returns:
the id for the release.
    public String getReleaseId() {
        String projectId = this.getProjectId();
        if (projectId == null) {
            this.log("Critical Error: projectId cannot be found for " + 
                     this.getProject() + ".  This could mean that the project "
                     + "does not exist OR that the user logging in does not " 
                     + "have access to that project.  " +
                     "Setting build status to UNSTABLE (or worse).");
            return null;
        }
        String packageId = this.getPackageId(projectId);
        if (packageId == null) {
            this.log("Critical Error: packageId cannot be found for " + 
                     this.getPackage() + ".  " +
                     "Setting build status to UNSTABLE (or worse).");
            return null;
        }
        String releaseId = this.getReleaseId(packageId);
        if (releaseId == null) {
            this.log("Critical Error: releaseId cannot be found for " + 
                     this.getRelease() + ".  " +
                     "Setting build status to UNSTABLE (or worse).");
            return null;
        }
        return releaseId;
    }

    
Get the project id for the project name.

Returns:
the matching project id, or null if none is found.
    public String getProjectId() {
        if (this. == null) {
            this.log("Cannot getProjectId, not logged in!");
            return null;
        }
        return CNHudsonUtil.getProjectId(this.this.getProject());
    }

    
Get the package id.

Parameters:
projectId the id of the project which contains this package.
Returns:
the package id, or null if none is found.
    public String getPackageId(String projectId) {
        if (this. == null) {
            this.log("Cannot getPackageId, not logged in!");
            return null;
        }
        return CNHudsonUtil.getPackageId(this.this.getPackage(), 
                                         projectId);
    }

    
Get the release id.

Parameters:
packageId the id of the package which contains this release.
Returns:
the release id, or null if none is found.
    public String getReleaseId(String packageId) {
        if (this. == null) {
            this.log("Cannot getReleaseId, not logged in!");
            return null;
        }
        return CNHudsonUtil.getReleaseId(this.packageId
                                         this.getRelease());
    }

    
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) {
        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().getEnvVars();
        } else {
            envVars = build.getEnvVars();
        }
        try {
            return CommonUtil.getInterpreted(envVarsstr);
        } catch (IllegalArgumentException iae) {
            this.log(iae.getMessage());
            throw iae;
        }
    }

    

Returns:
the descriptor for CNFileRelease.
    public Descriptor<PublishergetDescriptor() {
        return ;
    }

    
Descriptor should be singleton.
    public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

    
The CNFileRelease Descriptor class.
    public static final class DescriptorImpl 
        extends BuildStepDescriptor<Publisher> {
        private static int unique = 0;
        DescriptorImpl() {
            super(CNFileRelease.class);
        }

        

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

        

Returns:
string to display for configuration screen.
        public String getDisplayName() {
            return "CollabNet File Release";
        }

        

Returns:
the url that contains the help files.
        public static String getHelpUrl() {
            return "/plugin/collabnet/filerelease/";
        }

        

Returns:
a relative url to the main help file.
        @Override
        public String getHelpFile() {
            return getHelpUrl() + "help-main.html";
        }

        

Returns:
true if there is auth data that can be inherited.
        public boolean canInheritAuth() {
            return getTeamForgeShareDescriptor().useGlobal();
        }

        
Allows this plugin to be used as a promotion task.

Parameters:
jobType a class to check for applicability.
Returns:
true if CNFileRelease is applicable to this job.
        public boolean isApplicable(java.lang.Class<? 
                                    extends hudson.model.AbstractProject
                                    jobType) {
            return true;
        }

        
Creates a new instance of CNFileRelease from a submitted form.

Parameters:
req config page parameters.
formData data specific to this section, in json form.
Returns:
new CNFileRelease object, instantiated from the configuration form vars.
Throws:
FormException
        public CNFileRelease newInstance(StaplerRequest req
                                         JSONObject formData
            throws FormException {
            boolean override_auth = false;
            String username = null;
            String password = null;
            String collabneturl = null;
            if (formData.has("override_auth")) {
                override_auth = true;
                Object authObject = formData.get("override_auth");
                if (authObject instanceof JSONObject) {
                    username = (String)((JSONObjectauthObject)
                        .get("username");
                    password = (String)((JSONObjectauthObject)
                        .get("password");
                    collabneturl = (String)((JSONObjectauthObject)
                        .get("collabneturl");
                } else if (authObject.equals(.)) {
                    username = (StringformData.get("username");
                    password = (StringformData.get("password");
                    collabneturl = (StringformData.get("collabneturl");
                } else {
                    override_auth = false;
                }
            } else if (!this.canInheritAuth()) {
                override_auth = true;
                username = (String)formData.get("username");
                password = (String)formData.get("password");
                collabneturl = (String)formData.get("collabneturl");
            }
            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 CNFileRelease(collabneturl
                                     username
                                     password
                                     (String)formData.get("project"),  
                                     (String)formData.get("package"), 
                                     (String)formData.get("release"), 
                                     CommonUtil.getBoolean("overwrite"
                                                           formData),
                                     patternsoverride_auth);
        }

        
Form validation for the CollabNet URL.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doCollabNetUrlCheck(StaplerRequest req
                                        StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.SoapUrlCheck(reqrsp).process();
        }
        
        
Check that a password is present and allows login.

Parameters:
req contains parameters from the config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doPasswordCheck(StaplerRequest req
                                    StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.LoginCheck(reqrsp).process();
        }
        
        
Form validation for the project field.

Parameters:
req contains parameters from the config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doProjectCheck(StaplerRequest req
                                   StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.ProjectCheck(reqrsp).process();
        }

        
Form validation for username.

Parameters:
req contains parameters from config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doRequiredCheck(StaplerRequest req
                                    StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.RequiredCheck(reqrsp).process();
        }

        
Form validation for package.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doPackageCheck(StaplerRequest req
                                   StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.PackageCheck(reqrsp).process();      
        }

        
Form validation for release.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doReleaseCheck(StaplerRequest req
                                   StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.ReleaseCheck(reqrsp).process();        
        }

        
Form validation for the file patterns.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
rsp contains http response data (unused).
Throws:
IOException
ServletException
        public void doUnRequiredInterpretedCheck(StaplerRequest req
                                                 StaplerResponse rsp
            throws IOExceptionServletException {
            new CNFormFieldValidator.UnrequiredInterpretedCheck(reqrsp)
                .process();
        }
        
        
Gets a list of projects to choose from and write them as a JSON string into the response data.

Parameters:
req contains parameters from the config.jelly.
rsp http response data.
Throws:
IOException
        public void doGetProjects(StaplerRequest reqStaplerResponse rsp
            throws IOException {
            new ComboBoxUpdater.ProjectsUpdater(reqrsp).update();
        }

        
Gets a list of packages to choose from and write them as a JSON string into the response data.

Parameters:
req contains parameters from the config.jelly.
rsp http response data.
Throws:
IOException
        public void doGetPackages(StaplerRequest reqStaplerResponse rsp
            throws IOException {
            new ComboBoxUpdater.PackagesUpdater(reqrsp).update();
        }

        
Gets a list of releases to choose from and write them as a JSON string into the response data.

Parameters:
req contains parameters from the config.jelly.
rsp http response data.
Throws:
IOException
        public void doGetReleases(StaplerRequest reqStaplerResponse rsp
            throws IOException {
            new ComboBoxUpdater.ReleasesUpdater(reqrsp).update();
        }
    }
New to GrepCode? Check out our FAQ X