Adding users and groups to group members

Posted: 3 May 2009 in CSSDK, Groups, Java, Security, Teamsite, URLExternalTask, Users, Workflows

Once you know how to retrieve users and groups from the client, it becomes easy to add members to the group through the addUsers() method which takes an array of (validated) users.

String userNameToAdd="johndoe";
CSGroup someGroup = client.getGroup("marketing",true);
CSUser[] usersToAdd = {client.getUser(userNameToAdd,false)}
if (someGroup!=null){
    try {
        someGroup.addUsers(usersToAdd);
    } catch(CSException cse){
        System.err.println("user " + userNameToAdd + " to add to the group is invalid.");
        cse.printStackTrace();
    }
}

When passing an array of users, it is better to validate each of the users in the array. Having invalid or null CSUser objects in the array of users to add will cause the whole operation to fail. Thus, adding the users 1 by 1 might be a better solution. This is the case when retrieving a list of users from a workflow instantiation form, passed as a task variable. The list of users is comma-separated (with a space thrown in for good measure).

CSGroup someGroup = client.getGroup("marketing",true);
if (someGroup!=null){
    String userNames = task.getVariable("userNamesToAdd");
    String userNamesToAdd[] = null;
    if (userNames!=null){
        userNamesToAdd=userNames.replaceAll(" ","").split(",");
        for (String userNameToAdd:userNamesToAdd){
            CSUser[] usersToAdd = {client.getUser(userNameToAdd,false)};
            try {
                someGroup.addUsers(usersToAdd);
            } catch(CSException cse){
                System.err.println("user " + userNameToAdd + " to add to the group is invalid.");
                cse.printStackTrace();
            }
        }
    }
}

Adding a group as a sub-group is no more difficult with the addGroups function which takes an array of (validated) groups.

CSGroup someGroup = client.getGroup("marketing", true);
CSGroup someOtherGroup = client.getGroup("hr",true);
if (someGroup!=null && someOtherGroup!=null){
    CSGroup[] groupsToAdd={someOtherGroup};
    someGroup.addGroups[groupsToAdd];
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s