Sunday, 17 June 2018

OIM UI Branding - How to Change Logo on Identity Self Service Console?


Copy a new image file to the deployment directory:-

Copy the "CompanyLogo.png" file to the "$MW_HOME/Oracle_IDM1/server/apps/oim.ear/iam-consoles-faces.war/images/" folder.

Modify the Identity Self Service Console using the Web Composer:-

Login to Identity Self Service console using "xelsysadm" credential and create a new sandbox and activate it.
























Click on customize on top right corner of the Identity console.


Click on Structure tab.
















Change the "Short Desc" field from "Oracle" to <COMPANY_NAME>.

Click on highlighted drop down.

Click on "Expression Builder".

Remove old value i.e #{attrs.logoShortDesc} and put new value.

























Click on "OK".




















This changes the tool tip text that is displayed when the cursor is moved over the image.


Now change the company logo.

Click on highlighted drop down.




























Click on "Expression Builder".























Remove old value i.e #{attrs.logoImagePath } and enter new value as http://<HOSTNAME>:<PORT>/oim/images/companylogo.png

























Click on "OK".





















Close this window.

















Publish the sandbox.















Note: By default, the Oracle logo is 119x25 pixels (Width X height). Therefore, you can use a custom logo of the same dimensions. If you want a bigger logo, then it requires CSS changes.

Happy Learning!!!

OIM API - How to Get OIM Database Connection through the OIM Client?

public void getDatabaseConnectionExample(){
    //get OIM Client
    OIMClient oimClient = getOIMConnection();
   
    //OIM Schema Database Client
    com.thortech.xl.dataaccess.tcDataProvider dbProvider = null;
   
    try{
        //Establish connection to OIM Schema
        XLClientSecurityAssociation.setClientHandle(oimClient);
        dbProvider = new com.thortech.xl.client.dataobj.tcDataBaseClient();

        String query = "select usr_login from usr";           
        com.thortech.xl.dataaccess.tcDataSet usersDataSet = new com.thortech.xl.dataaccess.tcDataSet();
        usersDataSet.setQuery(dbProvider, query);
        usersDataSet.executeQuery();

        int numRecords = usersDataSet.getTotalRowCount();
       
        //iterate through each record
        for(int i = 0; i < numRecords; i++){
            usersDataSet.goToRow(i);
            System.out.println("User Login :: " + usersDataSet.getString("USR_LOGIN"));
        }
    }
  
    catch(Exception e){
        System.out.println("Exception occured while getting user details" + e);
    }
    finally{
        if(dbProvider != null){
            try{
                dbProvider.close();
            } catch(Exception e) {
                System.out.println("Exception occured while closing connection" + e);
            }
        }
       
        XLClientSecurityAssociation.clearThreadLoginSession();  
    }
}


Happy Learning!!!

OIM API - How to Get OIM Database Connection in Plugins?

public void getDatabaseConnectionExample() {
    Connection connection = null;
    try {
        connection = Platform.getOperationalDS().getConnection();

        String sql = "select usr_login from usr";
        PreparedStatement preparedStatement = null;

        preparedStatement = connection.prepareStatement(sql);
        ResultSet rs = preparedStatement.executeQuery();
        while(rs.next()){
            System.out.println("User Login :: " + rs.getString(1));
        }
    } catch (Exception e) {
        System.out.println("Exception occured while reading user details " + e);
    } finally {
        try {
            connection.close();
        } catch (Exception e) {
            System.out.println("Exception while closing connection : " + e);
        }
    }
}


Happy Learning!!!

OIM API - How to Remove Assigned Proxy from User?

To execute below code you have to add following jars in classpath:

  • commons-logging.jar

  • eclipselink.jar

  • jrf-api.jar

  • oimclient.jar

  • spring.jar

  • wlfullclient.jar

 

Stand Alone Code:

 

import java.util.HashSet;
import java.util.Hashtable;
import javax.security.auth.login.LoginException;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.api.UserManagerConstants;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.platform.OIMClient;

public class ProxyOps {
    OIMClient oimClient = null;
    UserManager userManager = null;
   
    //identity self service details
    String username = "xelsysadm";
    String password = "<password>"; //xelsysadm password
    String t3url = "t3://<hostname>:<port>"; //OIM HostName and Port
    String authwl_location = "<location of authwl.conf file in your local machine>"; //eg. D:\\authwl.conf
      
    public void getOIMConnection(){
        System.out.println("getOIMConnection() : Start");
        //set system properties
        System.setProperty("java.security.auth.login.config", authwl_location);
        System.setProperty("OIM.AppServerType", "wls");
        System.setProperty("APPSERVER_TYPE", "wls");

        Hashtable oimenv = new Hashtable();
        oimenv.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
        oimenv.put(OIMClient.JAVA_NAMING_PROVIDER_URL,t3url);
        oimClient = new OIMClient(oimenv);
        try {
            oimClient.login(username, password.toCharArray());
            System.out.println("Connected");
        } catch (LoginException e) {
            e.printStackTrace();
        }
        System.out.println("getOIMConnection() : End");
    }
   
    public void removeUserProxy(String userLogin, String proxyUserLogin) {
        System.out.println("removeUserProxy() : Start");
       
        //get user manager service
        userManager = oimClient.getService(UserManager.class);
       
        try {
            //get proxy user key from user login
            String proxyUserKey = getUserKeyByUserLogin(proxyUserLogin);
           
            System.out.println("UserLogin :: " + userLogin + " " + "ProxyUserKey :: " + proxyUserKey);

            userManager.removeProxy(userLogin, proxyUserKey, true);
        }catch(Exception e) {
            e.printStackTrace();
        }
        System.out.println("removeUserProxy() : End");
    }

    public String getUserKeyByUserLogin(String userLogin){
        HashSet<String> attrsToFetch = new HashSet<String>();
        attrsToFetch.add(UserManagerConstants.AttributeName.USER_KEY.getId());
   
        try{    
            User user = userManager.getDetails(userLogin, attrsToFetch, true);
            return user.getEntityId();
        }catch(Exception e){
            System.out.println("Exception occured while fetching user key");
            return null;
        }
    }
   
    public static void main(String[] args) {
        try {
            ProxyOps obj = new ProxyOps();
            obj.getOIMConnection();
           
            String userLogin = "TestUser1";
            String proxyUserLogin = "ProxyUser1";
           
            obj.removeUserProxy(userLogin, proxyUserLogin);
           
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

 

Happy Learning!!! 

Saturday, 16 June 2018

OIM - SQL Query to Get Members of Admin Role.

select usr.usr_login
from admin_role_membership,admin_role,usr
where admin_role_membership.user_id = usr.usr_key
and admin_role_membership.role_id = admin_role.role_id
and admin_role.role_name = 'OrclOIMSystemAdministrator';


OIM API - How to Get Members of Admin Role?

public void getAdminRoleMembers(String adminRolename) {
    String logp = CN + "getAdminRoleMembers";
    logger.info(logp + "START");
    Connection connection = null;
    ResultSet rs = null;
    try {
        connection = Platform.getOperationalDS().getConnection();

        String sql = "select usr.usr_login from admin_role_membership,admin_role,usr where admin_role_membership.user_id = usr.usr_key and admin_role_membership.role_id = admin_role.role_id and admin_role.role_name = ?";


        PreparedStatement preparedStatement = null;
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, adminRolename);
        rs = preparedStatement.executeQuery();
        logger.info(logp + "Members count :: " + rs.getFetchSize());
       
        while(rs.next()){
            logger.info(logp + "User Login :: " + rs.getString(1));
        }
    } catch (Exception e) {
        logger.error(logp + " Exception while getting members of admin role " + e);
    } finally {
        try {
            rs.close();
            connection.close();
        } catch (Exception e) {
            logger.error(logp + " Exception while closing connection : " + e);
        }
    }
    logger.info(logp+ "END");
}


Happy Learning!!!

OIM API - How to Create Lookup in OIM?

public void createLookup(String LookupName) {
     final String logp = CN + ":: createLookup- ";
     logger.info(logp + "START");
     tcLookupOperationsIntf lookupOper = null;
    
     try{
         lookupOper = Platform.getService(tcLookupOperationsIntf.class);
         logger.info(logp + " Creating Lookup : " + LookupName);
        
         //Invoking Lookup Create Operation
         lookupOper.addLookupCode(LookupName);
     }catch(Exception e){
         LOGGER.error(logp + "Exception occurred while creating lookup - " + e.getMessage(), e);
     }
    
     LOGGER.debug(logp + "END");
 }


Happy Learning!!! 

OIM API - Code Snippet to Remove Lookup Value.

public void removeLookupValue(String Key, String Lookup, boolean caseSensitive) {
    final String logp = CN + "::removeLookupValue - ";
    LOGGER.debug(logp + "START");
    Map searchFor = new HashMap();
    searchFor.put("Lookup Definition.Lookup Code Information.Code Key", Key);
    tcLookupOperationsIntf lookupService = null;
    try {
        lookupService = (tcLookupOperationsIntf) Platform.getService(tcLookupOperationsIntf.class);
        tcResultSet results = lookupService.getLookupValues(Lookup, searchFor);
        for (int i = 0; i < results.getRowCount(); i++) {
            results.goToRow(i);
            String key = results.getStringValue("Lookup Definition.Lookup Code Information.Code Key");
            if (!caseSensitive && key.equalsIgnoreCase(Key)) {
                lookupService.removeLookupValue(Lookup, key);
            } else if (caseSensitive && key.equals(Key)) {
                lookupService.removeLookupValue(Lookup, key);
            }
        }
    } catch (Exception e) {
        LOGGER.error(logp + "Exception occurred - " + e.getMessage(), e);
    }

    LOGGER.debug("END");
}


Happy Learning!!!

OIM API - Code Snippet to Add Entries in the Lookup.

public void addLookupValues(HashMap<String, String> lookupMap, String lookupName) throws Exception {
    String logp = CN + " :: addLookupValues - ";
    logger.info(logp + "START");
    tcLookupOperationsIntf lookupService = Platform.getService(tcLookupOperationsIntf.class);
    Set<String> set = lookupMap.keySet();
    Iterator iter = set.iterator();
    while (iter.hasNext()) {
        String key = (String)iter.next();
        if (!("".equalsIgnoreCase(lookupService.getDecodedValueForEncodedValue(lookupName,key).trim()))){
            logger.info(logp + "Value : " + key + " already in lookup. Updating the value");
            lookupService.removeLookupValue(lookupName, key);
            lookupService.addLookupValue(lookupName,key, lookupMap.get(key), "en","US"); 
        }
        else{
            logger.info(logp + "Value : " + key + " not present in lookup. Adding the value");
            lookupService.addLookupValue(lookupName,key, lookupMap.get(key), "en","US"); 
        }
    }
    logger.info(logp + "Lookup is appened with the new values");
    logger.info(logp + "END");
}


Happy Learning!!!

OIM API - Update the Group Name for Specified Lookup.

public void updateLookupGroupName(String groupName, String lookupName) {
    String logp = CN + "updateLookupGroupName";
    logger.info(logp + "START");
    Connection connection = null;
    try {
        connection = Platform.getOperationalDS().getConnection();

        String sql = "update lku set lku_group = ? where lku_type_string_key = ?";
        PreparedStatement preparedStatement = null;

        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, groupName);
        preparedStatement.setString(2, lookupName);
        preparedStatement.executeUpdate();
    } catch (Exception e) {
        logger.error(logp + " Exception while updating group name: " + e);
    } finally {
        try {
            connection.close();
        } catch (Exception e) {
            logger.error(logp + " Exception while closing connection : " + e);
        }
    }
    logger.info(logp+ "END");
}


Happy Learning!!!

OIM API - Code Snippet to Get Organization Details by Organization Name.

public void getOrganizationDetails(String orgName) {
        OrganizationManager orgManager = Platform.getService(OrganizationManager.class);
        Organization org;
        try{
            org = orgManager.getDetails(orgName, null, true);
           
            System.out.println("Organization ID :: " + org.getEntityId());
            System.out.println("Organization Name :: " + org.getAttribute(OrganizationManagerConstants.AttributeName.ORG_NAME.getId()));
            System.out.println("Parent Organization Name :: " + org.getAttribute(OrganizationManagerConstants.AttributeName.ORG_PARENT_NAME.getId()));
            System.out.println("Organization Password Policy Name :: " + org.getAttribute(OrganizationManagerConstants.AttributeName.ORG_PASSWORD_POLICY_NAME.getId()));
        } catch (OrganizationManagerException e) {
            System.out.println("Exception occured while fetching organization details");
        }
}


Happy Learning!!!

OIM API - Code Snippet to Get Admin Role Details by Admin Role Name.

private void getAdminRoleDetails(String adminRoleName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = Platform.getService(AdminRoleService.class);
       
        //get admin role object
        AdminRole adminRole = adminRoleSvc.getAdminRole(adminRoleName);

        System.out.println("Admin Role ID :: " + adminRole.getRoleId());
        System.out.println("Admin Role Name :: " + adminRole.getRoleName());
        System.out.println("Admin Role Display Name :: " + adminRole.getRoleDisplayName());
        System.out.println("Admin Role Description :: " + adminRole.getRoleDescription());
}



OIM API - Code Snippet to Get all Admin Roles Assigned to User.

public void getAllAdminRolesAssignedToUser(String userLogin, String orgName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = oimClient.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){
            System.out.println("***********************************");
            System.out.println("Admin Role ID :: " + membership.getAdminRoleId());
            System.out.println("Admin Role Name :: " + membership.getAdminRoleName());
            System.out.println("***********************************");
        }       
}

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!!!

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!!!

OIM API - Code Snippet to Assign Admin Role to User.

public void assignAdminRoleToUser(String adminRoleName, String userLogin, String orgName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = Platform.getService(AdminRoleService.class);
       
        //get admin role object by admin role name
        AdminRole adminRole = getAdminRoleByName(adminRoleName);
        if(null == adminRole){
            System.out.println("Admin role <"+adminRole+"> is not present");
            return;
        }
       
        //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;
        }
       
        //Create a new membership object
        AdminRoleMembership membership = new AdminRoleMembership();
        membership.setAdminRole(adminRole);
        membership.setUserId(usrKey);
        membership.setScopeId(orgKey);
        membership.setHierarchicalScope(true);
       
        adminRoleSvc.addAdminRoleMembership(membership); 
        System.out.println("Admin Role Successfully Assigned to the User: " + userLogin);
}


private AdminRole getAdminRoleByName(String adminRoleName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = Platform.getService(AdminRoleService.class);
       
        List<AdminRole> adminRoles = adminRoleSvc.getScopedAdminRoles();
        Iterator adminRolesIter = adminRoles.iterator();
        while (adminRolesIter.hasNext()) {
            AdminRole adminRole = (AdminRole)adminRolesIter.next();
          if (adminRole.getRoleName().equals(adminRoleName)) {
              return adminRole;
          }
        }
        return null;
}
 
private String getOrganizationID(String orgName) {
        OrganizationManager orgManager = Platform.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;
        }
}
   
public String getUserKeyByUserLogin(String userLogin){
        HashSet<String> attrsToFetch = new HashSet<String>();
        attrsToFetch.add(UserManagerConstants.AttributeName.USER_KEY.getId());
   
        try{    
            //get user manager service
            UserManager userService = Platform.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!!!

OIM API - Admin Role Operations.

To execute below code you have to add following jars in classpath:

  • commons-logging.jar

  • eclipselink.jar

  • jrf-api.jar

  • oimclient.jar

  • spring.jar

  • wlfullclient.jar

 

Stand Alone Code:

 

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.security.auth.login.LoginException;
import oracle.iam.identity.exception.OrganizationManagerException;
import oracle.iam.identity.orgmgmt.api.OrganizationManager;
import oracle.iam.identity.orgmgmt.vo.Organization;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.api.UserManagerConstants;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.platform.OIMClient;
import oracle.iam.platform.authopss.vo.AdminRole;
import oracle.iam.platform.authopss.vo.AdminRoleMembership;
import oracle.iam.platformservice.api.AdminRoleService;

public class AdminRoleOperation {
       OIMClient oimClient = null;
         
       //identity self service details
       String username = "xelsysadm";
       String password = "<password>"; //xelsysadm password
       String t3url = "t3://<hostname>:<port>"; //OIM HostName and Port
       String authwl_location = "<location of authwl.conf file in your local machine>"; //eg. D:\\authwl.conf
     
public void getOIMConnection(){
       //set system properties
       System.setProperty("java.security.auth.login.config", authwl_location);
       System.setProperty("OIM.AppServerType", "wls");
       System.setProperty("APPSERVER_TYPE", "wls");
   
       Hashtable oimenv = new Hashtable();
       oimenv.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
       oimenv.put(OIMClient.JAVA_NAMING_PROVIDER_URL,t3url);
       oimClient = new OIMClient(oimenv);
       try {
           oimClient.login(username, password.toCharArray());
           System.out.println("Connected!!!");
       } catch (LoginException e) {
           e.printStackTrace();
       }
}
     
public void assignAdminRoleToUser(String adminRoleName, String userLogin, String orgName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = oimClient.getService(AdminRoleService.class);
       
        //get admin role object by admin role name
        AdminRole adminRole = getAdminRoleByName(adminRoleName);
        if(null == adminRole){
            System.out.println("Admin role <"+adminRole+"> is not present");
            return;
        }
       
        //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;
        }
       
        //Create a new membership object
        AdminRoleMembership membership = new AdminRoleMembership();
        membership.setAdminRole(adminRole);
        membership.setUserId(usrKey);
        membership.setScopeId(orgKey);
        membership.setHierarchicalScope(true);
       
        adminRoleSvc.addAdminRoleMembership(membership); 
        System.out.println("Admin Role Successfully Assigned to the User: " + userLogin);
}
   
public void revokeAdminRoleFromUser(String adminRoleName, String userLogin, String orgName) {   
        boolean isRemoved = false;
        //initialize admin role service
        AdminRoleService adminRoleSvc = oimClient.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 void getAllAdminRolesAssignedToUser(String userLogin, String orgName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = oimClient.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){
            System.out.println("***********************************");
            System.out.println("Admin Role ID :: " + membership.getAdminRoleId());
            System.out.println("Admin Role Name :: " + membership.getAdminRoleName());
            System.out.println("***********************************");
        }       
}

private AdminRole getAdminRoleByName(String adminRoleName) {
        //initialize admin role service
        AdminRoleService adminRoleSvc = oimClient.getService(AdminRoleService.class);
       
        List<AdminRole> adminRoles = adminRoleSvc.getScopedAdminRoles();
        Iterator adminRolesIter = adminRoles.iterator();
        while (adminRolesIter.hasNext()) {
            AdminRole adminRole = (AdminRole)adminRolesIter.next();
          if (adminRole.getRoleName().equals(adminRoleName)) {
              return adminRole;
          }
        }
        return null;
}
 
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;
        }
}
   
public 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;
        }
}

public static void main(String[] args) {
        try {
            AdminRoleOperation obj = new AdminRoleOperation();
            obj.getOIMConnection();
           
            //Assign Admin Role to User
            obj.assignAdminRoleToUser("OrclOIMSystemAdministrator", "TestUser1", "Top");
           
            //Revoke Admin Role from User
            obj.revokeAdminRoleFromUser("OrclOIMSystemAdministrator", "TestUser1", "Top");
           
            //get All Admin Roles Assigned to User
            obj.getAllAdminRolesAssignedToUser("TestUser1", "Top");
           
            //get Admin Role by Name
            obj.getAdminRoleByName("OrclOIMSystemAdministrator");

        } catch (Exception e) {
            System.out.println("Exception occured :: " + e.getMessage());
        }
}
}

Happy Learning!!!

Sunday, 10 June 2018

OIM API - Frequently Used Lookup Operations.

Read Lookup Values:-

public Map<String, String> getLookupMap(String lookupName) {
        final String logp = CN + " :: getLookupMap - ";
        LOGGER.debug(logp + "START");
        Map<String, String> lookupMap = new HashMap<String, String>();
        tcLookupOperationsIntf lookupService = Platform.getService(tcLookupOperationsIntf.class);
        try {
            tcResultSet resultSet = lookupService.getLookupValues(lookupName);
            String codeKey, meaningValue;
            for (int i = 0; i < resultSet.getRowCount(); i++) {
                resultSet.goToRow(i);
                codeKey = resultSet.getStringValue("Lookup Definition.Lookup Code Information.Code Key");
                meaningValue = resultSet.getStringValue("Lookup Definition.Lookup Code Information.Decode");
                lookupMap.put(codeKey, meaningValue);
                LOGGER.info(logp + " \nLookup Key: [" + codeKey + "], Lookup Value:[" + meaningValue + "])");
            }
        } catch (tcAPIException e) {
            LOGGER.severe(logp + "Exception occured while reading lookup " + e.getMessage());
            e.printStackTrace();
        } catch (tcInvalidLookupException e) {
            LOGGER.severe(logp + "Exception occured while reading lookup " + e.getMessage());
            e.printStackTrace();
        } catch (tcColumnNotFoundException e) {
            LOGGER.severe(logp + "Exception occured while reading lookup " + e.getMessage());
            e.printStackTrace();
        }
        LOGGER.debug(logp + "END");
        return lookupMap;
    }



 Create Lookup:-
 public void createLookup(String LookupName) {
     final String logp = CN + ":: createLookup- ";
     logger.info(logp + "START");
     tcLookupOperationsIntf lookupOper = null;
    
     try{
         lookupOper = Platform.getService(tcLookupOperationsIntf.class);
         logger.info(logp + " Creating Lookup : " + LookupName);
        
         //Invoking Lookup Create Operation
         lookupOper.addLookupCode(LookupName);
     }catch(Exception e){
         LOGGER.error(logp + "Exception occurred while creating lookup - " + e.getMessage(), e);
     }
    
     LOGGER.debug(logp + "END");
 } 



Add Lookup Values:-
public void addLookupValues(HashMap<String, String> lookupMap, String lookupName) throws Exception {
    String logp = CN + " :: addLookupValues - ";
    logger.info(logp + "START");
    tcLookupOperationsIntf lookupService = Platform.getService(tcLookupOperationsIntf.class);
    Set<String> set = lookupMap.keySet();
    Iterator iter = set.iterator();
    while (iter.hasNext()) {
        String key = (String)iter.next();
        if (!("".equalsIgnoreCase(lookupService.getDecodedValueForEncodedValue(lookupName,key).trim()))){
            logger.info(logp + "Value : " + key + " already in lookup. Updating the value");
            lookupService.removeLookupValue(lookupName, key);
            lookupService.addLookupValue(lookupName,key, lookupMap.get(key), "en","US"); 
        }
        else{
            logger.info(logp + "Value : " + key + " not present in lookup. Adding the value");
            lookupService.addLookupValue(lookupName,key, lookupMap.get(key), "en","US"); 
        }
    }
    logger.info(logp + "Lookup is appened with the new values");
    logger.info(logp + "END");
}



Remove Lookup Value:-
public void removeLookupValue(String Key, String Lookup, boolean caseSensitive) {
    final String logp = CN + "::removeLookupValue - ";
    LOGGER.debug(logp + "START");
    Map searchFor = new HashMap();
    searchFor.put("Lookup Definition.Lookup Code Information.Code Key", Key);
    tcLookupOperationsIntf lookupService = null;
    try {
        lookupService = (tcLookupOperationsIntf) Platform.getService(tcLookupOperationsIntf.class);
        tcResultSet results = lookupService.getLookupValues(Lookup, searchFor);
        for (int i = 0; i < results.getRowCount(); i++) {
            results.goToRow(i);
            String key = results.getStringValue("Lookup Definition.Lookup Code Information.Code Key");
            if (!caseSensitive && key.equalsIgnoreCase(Key)) {
                lookupService.removeLookupValue(Lookup, key);
            } else if (caseSensitive && key.equals(Key)) {
                lookupService.removeLookupValue(Lookup, key);
            }
        }
    } catch (Exception e) {
        LOGGER.error(logp + "Exception occurred - " + e.getMessage(), e);
    }

    LOGGER.debug("END");
}



Empty Lookup:-
public void emptyLookup(String lookupName){
    final String logp = CN + " ::emptyLookup - ";
    LOGGER.debug(logp + "START");
    tcLookupOperationsIntf lookupService = null;
   
    try {
        lookupService = Platform.getService(tcLookupOperationsIntf.class);
       
        HashMap<String, String> lookupMap = getLookupMap(lookupName);
        if (lookupMap.size() > 0) {
            for (String key : lookupMap.keySet()) {
                lookupService.removeLookupValue(lookupName, key);
            }
            LOGGER.debug(logp + "Lookup - " + lookupName + " emptied successfully");
        } else {
            LOGGER.debug(logp + "Lookup - " + lookupName + " is already empty.");
        }
    } catch (Exception e) {
        LOGGER.error(logp + "Exception in emptyLookup()" + e.getMessage());
    }

    LOGGER.debug(logp + "END");
}



Check If Lookup Present in OIM:-
public boolean isLookupPresent(String lookupName) throws Exception {
    String logp = CN + " :: isLookupPresent - ";
    logger.info(logp + "START");       
    boolean isLookupPresent = true;
    tcLookupOperationsIntf lookupService = Platform.getService(tcLookupOperationsIntf.class);
    Map lookupMap = new HashMap();  
    lookupMap.put("Lookup Definition.Lookup Code Information.Code Key",lookupName);
    tcResultSet resultSet = lookupService.findAvailableLookups(lookupMap);
    if(resultSet.getRowCount() == 0){
        isLookupPresent = false;
    }
    return isLookupPresent;
    logger.info(logp + "END");
}



Check if Lookup is Empty:-
public boolean isLookupEmpty(String lookupName) throws Exception {
    final String logp = CN + " ::
isLookupEmpty- ";
    LOGGER.debug(logp + "START");
    HashMap<String, String> lookupMap = new HashMap<String, String>();
    try {
        lookupMap = getLookupMap(lookupName);
    } catch (Exception e) {
        LOGGER.error(logp + "Exception in getLookupEmptyStatus()" + e.getMessage());
    }
    LOGGER.debug(logp + "END");

    return lookupMap.isEmpty();
}



Update the Group Name for Specified Lookup:-
public void updateLookupGroupName(String groupName, String lookupName) {
    String logp = CN + "updateLookupGroupName";
    logger.info(logp + "START");
    Connection connection = null;
    try {
        connection = Platform.getOperationalDS().getConnection();

        String sql = "update lku set lku_group = ? where lku_type_string_key = ?";
        PreparedStatement preparedStatement = null;

        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, groupName);
        preparedStatement.setString(2, lookupName);
        preparedStatement.executeUpdate();
    } catch (Exception e) {
        logger.error(logp + " Exception while updating group name: " + e);
    } finally {
        try {
            connection.close();
        } catch (Exception e) {
            logger.error(logp + " Exception while closing connection : " + e);
        }
    }
    logger.info(logp+ "END");
}


Happy Learning!!!