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.Extension;
 
 
 
 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 Notifier {
     // 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 Secret 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.
rpackage 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. = CNHudsonUtil.sanitizeCollabNetUrl(url);
        this. = username;
        this. = Secret.fromString(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 logConsole(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.logConsole(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.==null ? null : this..toString();
        } 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[projects.size()]);
    }

    

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[packages.size()]);
    }

    

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[releases.size()]);
    }
    @Override
        return .;
    }

    
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.
    @Override
    public boolean perform(AbstractBuild<?, ?> buildLauncher launcher
                           BuildListener listenerthrows IOExceptionInterruptedException {
        this.setupLogging(listener);
        this. = CNHudsonUtil.getCollabNetApp(this.getCollabNetUrl(), 
                                                this.getUsername(), 
                                                this.getPassword());
        if (this. == null) {
            this.logConsole("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:
numUploaded
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 the release id
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:
path 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.
Throws:
IOException
InterruptedException
    public int uploadFiles(AbstractBuild<?, ?> buildString releaseIdthrows IOExceptionInterruptedException {
        int numUploaded = 0;
        final FrsApp fa = new FrsApp(this.);
        this.logConsole("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.logConsole("File pattern " + uninterp_fp + " contained a bad "
                         + "env var.  Skipping.");
                continue;
            }
            if (file_pattern.equals("")) {
                // skip empty fields
                continue;
            }
            FilePath[] filePaths = this.getFilePaths(buildfile_pattern);
            for (FilePath uploadFilePath : filePaths) {
                // 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.logConsole("Deleted previously uploaded file: " +
                                     uploadFilePath.getName());
                        } catch (RemoteException re) {
                            this.log("delete file"re);
                        }
                    } else {
                        this.logConsole("File " + uploadFilePath.getName() +
                                 " already exists in the file release " +
                                 "system and overwrite is set to false.  " +
                                 "Skipping.");
                        continue;
                    }
                }
                try {
                    // HACK: start
                    // All soap App must be preloaded by current classloader for "invoke" call below to work on slave
                    new FileStorageApp(this.);
                    // HACK: end
                    String path = uploadFilePath.act(
                        new RemoteFrsFileUploader(getCollabNetUrl(), getUsername(), .getSessionId(), releaseId)
                    );
                    this.logConsole("Uploaded file " + uploadFilePath.getName() + " -> " + this.getFileUrl(path));
                    numUploaded++;
                } catch (RemoteException re) {
                    this.log("upload file"re);
                } catch (IOException ioe) {
                    this.logConsole("Could not upload file due to IOException: "
                             + ioe.toString());
                    ioe.printStackTrace(this..error("error"));
                } catch (InterruptedException ie) {
                    this.logConsole("Could not upload file due to " +
                             "InterruptedException: " + ie.getMessage());
                }
                
            }
        }
        return numUploaded;
    }

    
Private class that can perform upload function.
    private static class RemoteFrsFileUploader implements FileCallable<String> {
        private String mServerUrl;
        private String mUsername;
        private String mSessionId;
        private String mReleaseId;

        
Constructor. Needs to have old sessionId, since the uploaded file is only available to the same session.

Parameters:
serverUrl collabnet serverUrl
username collabnet username
sessionId collabnet sessionId
releaseId the id of the release to create file in
        public RemoteFrsFileUploader(String serverUrlString usernameString sessionIdString releaseId) {
             = serverUrl;
             = username;
             = sessionId;
             = releaseId;
        }

        

See also:
FileCallable.invoke(File, VirtualChannel)
        public String invoke(File fVirtualChannel channelthrows IOException {
            CollabNetApp cnApp = CNHudsonUtil.recreateCollabNetApp();
            FileStorageApp fsApp = new FileStorageApp(cnApp);
            FrsApp frsApp = new FrsApp(cnApp);
            String fileId = fsApp.uploadFile(f);
            FrsFileSoapDO fileDO = frsApp.createFrsFile(f.getName(), CNFileRelease.getMimeType(f), fileId);
            return fileDO.getPath();
        }
    }

    
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;
        if (FreeStyleProject.class.isInstance(build.getProject())) { // generic instanceof causes compilation error
            // our standard project
            workspace = build.getWorkspace();
        } else {
            // promoted build - use the project's workspace, since the build doesn't always account for custom workspace
            // may be a bug with promoted build?
            workspace = build.getProject().getRootProject().getWorkspace();
        }
        String logEntry = "Searching ant pattern '" + pattern + "'";
        FilePath[] uploadFilePaths = new FilePath[0];
        try {
            uploadFilePaths = workspace.list(pattern);
            logEntry += " in " + workspace.absolutize().getRemote();
        } catch (IOException ioe) {
            this.logConsole("Could not list workspace due to IOException: "
                     + ioe.getMessage());
        } catch (InterruptedException ie) {
            this.logConsole("Could not list workspace due to " +
                     "InterruptedException: " + ie.getMessage());
        }
        logEntry += " : found " + uploadFilePaths.length + " entry(ies)";
        logConsole(logEntry);
        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.logConsole("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.logConsole("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.logConsole("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.logConsole("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.logConsole("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.logConsole("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.logConsole("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)
            throws IOExceptionInterruptedException {
        Map<StringStringenvVars;
        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 {
            return CommonUtil.getInterpreted(envVarsstr);
        } catch (IllegalArgumentException iae) {
            this.logConsole(iae.getMessage());
            throw iae;
        }
    }

    
The CNFileRelease Descriptor class.
    @Extension
    public static final class DescriptorImpl 
        extends BuildStepDescriptor<Publisher> {
        private static int unique = 0;
        public 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.
        @Override
        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.
        @Override
        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
        @Override
        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:
value url
Returns:
the form validation
        public FormValidation doCollabNetUrlCheck(@QueryParameter String value) {
            return CNFormFieldValidator.soapUrlCheck(value);
        }
        
        
Check that a password is present and allows login.

Parameters:
req contains parameters from the config.jelly.
Returns:
the form validation
        public FormValidation doPasswordCheck(StaplerRequest req) {
            return CNFormFieldValidator.loginCheck(req);
        }
        
        
Form validation for the project field.

Parameters:
req contains parameters from the config.jelly.
Returns:
the form validation
        public FormValidation doProjectCheck(StaplerRequest req) {
            return CNFormFieldValidator.projectCheck(req);
        }

        
Form validation for username.

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

        
Form validation for package.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
Returns:
the form validation
        public FormValidation doPackageCheck(StaplerRequest req) {
            return CNFormFieldValidator.packageCheck(req);
        }

        
Form validation for release.

Parameters:
req StaplerRequest which contains parameters from the config.jelly.
Returns:
the form validation
        public FormValidation doReleaseCheck(StaplerRequest req) {
            return CNFormFieldValidator.releaseCheck(req);
        }

        
Form validation for the file patterns.

Parameters:
value
name of field
Returns:
the form validation
                @QueryParameter String value, @QueryParameter String name) {
            return CNFormFieldValidator.unrequiredInterpretedCheck(valuename);
        }
        
        
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