Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package hudson.plugins.collabnet.auth;
  
  import hudson.Extension;
  import hudson.model.Item;
  import hudson.model.Job;
 
 import java.util.List;
Job property to associate a Hudson job with a CollabNet Project for Authorization purposes (used with CollabNet Authorization).
 
 public class CNAuthProjectProperty extends JobProperty<Job<?, ?>> {
     public static Permission CONFIGURE_PROPERTY = .;
     private transient boolean mIsNotLoadedFromDisk = false;
     private transient String project = null;
     private String projectId = null;
     private boolean createRoles = false;
     private boolean grantDefaultRoles = false;
     private static Logger log = Logger.getLogger("CNAuthProjectProperty");
     private static Collection<StringdefaultAdminRoles = 
         Collections.emptyList();
     private static Collection<StringdefaultUserRoles = 
         Collections.emptyList();

    
Constructor

Parameters:
projectName name of project to tie the auth to
createRoles true to create special hudson roles
grantDefaults true to grant default roles to project members
isNotLoadedFromDisk true for newly instantiated jobs
 
     public CNAuthProjectProperty(String projectNameBoolean createRoles,
                                  Boolean grantDefaultsboolean isNotLoadedFromDisk) {
         this. = projectName;
         this. = createRoles;
         this. = grantDefaults;
         if (this. || this.) {
             this.loadRoles();
         }
          = isNotLoadedFromDisk;
     }

    
Determine the project id.
 
     private void loadProjectIdIfNecessary() {
         if (CommonUtil.isEmpty() && !CommonUtil.isEmpty()) {
             CNConnection conn = CNConnection.getInstance();
             if (conn == null) {
                 return;
             }
 
              = conn.getProjectId();
 
             if (!) {
                 if (this. != null) {
                     try {
                          = true;
                         this..save(); // should save the conf file for the job
                     } catch (IOException e) {
                         .info("Failed to modify config file for migration of project name to project id");
                     }
                 }
             }
         }
     }

    

Returns:
the name of the CollabNet project.
 
     public String getProject() {
         loadProjectIdIfNecessary();
 
         if (!CommonUtil.isEmpty()) {
             // always use the name from project id if project id exists - this allows us to address scenario where
             // while the app is running, the project name was changed on the server
             CNConnection conn = CNConnection.getInstance();
             if (conn != null) {
                 return conn.getProjectName();
             }
         }
 
         return "";
    }

    

Returns:
the id of the TeamForge project.
    public String getProjectId() {
        loadProjectIdIfNecessary();
        return ;
    }

    
Set the project id and reprocure the corresponding project name

Parameters:
projectId project id
    public void setProjectId(String projectId) {
        this. = projectId;
    }

    

Returns:
true if creating the roles on the CollabNet server should be attempted.
    public boolean createRoles() {
        return this.;
    }

    

Returns:
true if the default roles should be added.
    public boolean grantDefaultRoles() {
        return this.;
    }

    

Returns:
the default user roles. Lazily initialized.
            . = new ArrayList<String>();
            ..add("Hudson Read");
        }
    }

    

Returns:
the default admin roles. Lazily initialized.
            . = 
                CNProjectACL.CollabNetRoles.getNames();
        }
    }

    
Load the roles into CSFE, if they are not already present. Requires the logged in user to be a project admin in the CollabNet project.
    private void loadRoles() {
        String projectIdStr = getProjectId();
        if (!CommonUtil.isEmpty(projectIdStr)) {
            CNConnection conn = CNConnection.getInstance();
            if (conn == null) {
                .warning("Cannot loadRoles, incorrect authentication type.");
                return;
            }
            if (this.createRoles()) {
                List<StringroleNames = new ArrayList<String>();
                List<Stringdescriptions = new ArrayList<String>();
                for (CollabNetRole role: CNProjectACL.CollabNetRoles.getAllRoles()) {
                    roleNames.add(role.getName());
                    descriptions.add(role.getDescription());
                }
                conn.addRoles(projectIdStrroleNamesdescriptions);
            }
            
            if (this.grantDefaultRoles()) {
                // load up some default roles
                // this should be an option later
                conn.grantRoles(projectIdStrthis.getDefaultUserRoles(), conn.getUsers(projectIdStr));
                conn.grantRoles(projectIdStrthis.getDefaultAdminRoles(), conn.getAdmins(projectIdStr));
            }
        }   
    }

    
Descriptor class.
    @Extension
    public static class DescriptorImpl extends JobPropertyDescriptor {
        public DescriptorImpl() {
            super(CNAuthProjectProperty.class);
        }

        

Parameters:
req config page parameters.
Returns:
new CNAuthProjectProperty object, instantiated from the configuration form vars.
Throws:
hudson.model.Descriptor.FormException
        @Override
        public JobProperty<?> newInstance(StaplerRequest req,
                                          JSONObject formData
            throws FormException {
            Boolean createRoles = .;
            Boolean grantDefaults = .;
            if (formData.get("createRoles") != null) {
                createRoles = .;
            }
            if (formData.get("grantDefaults") != null) {
                grantDefaults = .;
            }
            String projectName = (String)formData.get("project");
            String storedProjectId = (String)formData.get("storedProjectId");
            CNAuthProjectProperty prop = new CNAuthProjectProperty(projectNamecreateRolesgrantDefaultstrue);
            prop.loadProjectIdIfNecessary();
            if (!CommonUtil.isEmpty(prop.getProject()) && CommonUtil.isEmpty(prop.getProjectId())) {
                // means we can't find the specified project name - prevent overriding
                prop.setProjectId(storedProjectId);
            }
            return prop;
        }

        

Returns:
string to display.
        @Override
        public String getDisplayName() {
            return "Associated CollabNet Project";
        }
        
        

Parameters:
jobType
Returns:
true when the CNAuthorizationStrategy is in effect.
        @Override
	public boolean isApplicable(Class<? extends JobjobType) {
            // only applicable when using CNAuthorizationStrategy
            return Hudson.getInstance().getAuthorizationStrategy() 
                instanceof CNAuthorizationStrategy;
        }

        
Form validation for the project field.

Parameters:
project
        public FormValidation doProjectCheck(@QueryParameter String project) {
            if (CommonUtil.isEmpty(project)) {
                return FormValidation.warning("If left empty, all users will be able to configure and access this " +
                    "build");
            }
            CNConnection conn = CNConnection.getInstance();
            if (conn == null) {
                return FormValidation.warning("Cannot check project name, improper" +
                        " authentication type.");
            }
            String projectId = conn.getProjectId(project);
            boolean superUser = conn.isSuperUser();
            boolean hudsonAdmin = Hudson.getInstance().getACL()
                .hasPermission(.);
            if (CommonUtil.isEmpty(projectId)) {
                if (superUser) {
                    return FormValidation.error("This project does not exist.");
                } else {
                    return FormValidation.error("The current user does not have access " +
                          "to this project.  This setting change will not be saved.");
                }
            }
            if (superUser) {
                // all other errors should not be valid for a
                // superuser, since superusers are Hudson Admins
                // (so all-powerful in the Hudson realm) and also
                // all-powerful in the CollabNet server.
                return FormValidation.ok();
            }
            if (!conn.isProjectAdmin(projectId)) {
                return FormValidation.warning("The current user is not a project admin in " +
                     "the project, so he/she cannot create or " +
                     "grant roles.");
            }
            if (hudsonAdmin) {
                // no more errors apply to the Hudson Admin, since
                // admins will never be locked out of this page.
                return FormValidation.ok();
            }
            // check that the user will have configure permissions
            // on this page
            CNProjectACL acl = new CNProjectACL(projectId);
            if (!acl.hasPermission(
                                   .)) {
                CollabNetRole roleNeeded =
                    CNProjectACL.CollabNetRoles
                    .getGrantingRole(
                                     .);
                return FormValidation.warning("The current user does not have the '" +
                     roleNeeded.getName() + "' role in the " +
                     "project, which is required to configure " +
                     "this Hudson job.  If this project is chosen," +
                     " the current user will not have the power " +
                     "to change the project later, unless he/she " +
                     "is given this role.");
            }
            return FormValidation.ok();
        }

        
Get the project id for the given project

Parameters:
request the request
response the response
Throw:
IOException if we fail to write response
        public void doGetProjectId(StaplerRequest requestStaplerResponse responsethrows IOException {
            CNConnection conn = CNConnection.getInstance();
            String project = request.getParameter("project");
            String projectId;
            if (conn == null) {
                projectId = "";
            } else {
                projectId = conn.getProjectId(project);
            }
            response.setContentType("text/plain;charset=UTF-8");
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("projectName"project);
            jsonObj.put("projectId"projectId);
            response.getWriter().print(jsonObj.toString());
        }

        
Get a list of projects to choose from.

Returns:
an array of project names.
        public String[] getProjects() {
            Collection<Stringprojects = Collections.emptyList();
            CNConnection conn = CNConnection.getInstance();
            if (conn == null) {
                return new String[0];
            }
            projects = conn.getProjects();
            return projects.toArray(new String[0]);
        }

        

Returns:
the CollabNet server url.
        public String getCollabNetUrl() {
            CNConnection conn = CNConnection.getInstance();
            return conn.getCollabNetApp().getServerUrl();
        }
    }
New to GrepCode? Check out our FAQ X