Saturday, 16 June 2018

OIM API - Code Snippet to Revoke Admin Role from User.

public void revokeAdminRoleFromUser(String adminRoleName, String userLogin, String orgName) {   
        boolean isRemoved = false;
        //initialize admin role service
        AdminRoleService adminRoleSvc = Platform.getService(AdminRoleService.class);
       
        //get organization key by organization name
        String orgKey = getOrganizationID(orgName);
        if(null == orgKey){
            System.out.println("Organization <"+orgName+"> is not present");
            return;
        }
       
        //get user key by user login
        String usrKey = getUserKeyByUserLogin(userLogin);
        if(null == usrKey){
            System.out.println("User <"+userLogin+"> is not present");
            return;
        }
       
        List<AdminRoleMembership> memberships = adminRoleSvc.listUsersMembership(usrKey, null, orgKey, true, null);
        System.out.println("Memberships count :: " + memberships.size());
       
        for(AdminRoleMembership membership : memberships){
            if (membership.getAdminRoleName().equals(adminRoleName)) {
                isRemoved = adminRoleSvc.removeAdminRoleMembership(membership);
                break;
            }       
        }
       
        if(isRemoved){
            System.out.println("Admin Role Successfully Revoked from the User : " + userLogin);
        }else{
            System.out.println("Something went wrong");
        }
}
       
private String getOrganizationID(String orgName) {
        OrganizationManager orgManager = oimClient.getService(OrganizationManager.class);
        Organization org;
        try{
          org = orgManager.getDetails(orgName, null, true);
          return org.getEntityId();
        } catch (OrganizationManagerException e) {
            System.out.println("Exception occured while fetching org key");
            return null;
        }
}
   
private String getUserKeyByUserLogin(String userLogin){
        HashSet<String> attrsToFetch = new HashSet<String>();
        attrsToFetch.add(UserManagerConstants.AttributeName.USER_KEY.getId());
   
        try{    
            //get user manager service
            UserManager userService = oimClient.getService(UserManager.class);
          
            User user = userService.getDetails(userLogin, attrsToFetch, true);
            return user.getEntityId();
        }catch(Exception e){
            System.out.println("Exception occured while fetching user key");
            return null;
        }
}


Happy Learning!!!

No comments:

Post a Comment