Saturday, 24 March 2018

OIM API - Stand Alone Code to add Process Task for Bulk Users.

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 Thor.API.Exceptions.tcAPIException;
import Thor.API.Exceptions.tcColumnNotFoundException;
import Thor.API.Operations.TaskDefinitionOperationsIntf;       
import Thor.API.tcResultSet;
import Thor.API.Operations.tcProvisioningOperationsIntf;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.security.auth.login.LoginException;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.platform.OIMClient;
import oracle.iam.provisioning.api.ProvisioningService;
import oracle.iam.provisioning.vo.Account;

public class AddProcessTask { 

    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(){
            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 addProcessTask(List<String> userList, String appInst, String taskName, String accountStatus){
      try{
        ProvisioningService provService = oimClient.getService(ProvisioningService.class);
        tcProvisioningOperationsIntf provisioningOperationsIntf = oimClient.getService(tcProvisioningOperationsIntf.class);
        UserManager userManager = oimClient.getService(UserManager.class);
       
        for(String userLogin : userList){
            System.out.println("User Login - " + userLogin);
            User user = userManager.getDetails(userLogin, null, true);
 
            List<Account> provList = provService.getAccountsProvisionedToUser(user.getEntityId());
            System.out.println("No of accounts : " + provList.size() + " for user : " + user.getLogin());
           
            for (Account account : provList){
              System.out.println(account.getAppInstance().getApplicationInstanceName());
              if ((appInst.equals(account.getAppInstance().getApplicationInstanceName())) &&
                (account.getAccountStatus().equals(accountStatus))){
                long pInstKey = Long.parseLong(account.getProcessInstanceKey());
                long taskKey = getTaskKey(pInstKey, taskName);
                if(taskKey != 0L){
                  provisioningOperationsIntf.addProcessTaskInstance(taskKey, pInstKey);
                }
                System.out.println("Successfully added task " + taskName + " to " + appInst + "!!!");
              }else{
                System.out.println("None of the accounts match the app instance");
              }
            }
        }
      }catch (Exception e){
          System.out.println("Error occured while adding process task " + e.getMessage());
      }
 }
   
 public long getTaskKey(long prcInstKey, String taskName) throws tcAPIException,
                                                   tcAPIException, tcColumnNotFoundException{
          TaskDefinitionOperationsIntf taskDefnOpsIntf = oimClient.getService(TaskDefinitionOperationsIntf.class);
         
          if((taskName == null) || (taskName.length() == 0)){
            System.out.println("Task Name not found");
          }
         
          Map<String, String> tskSrchFilter = new HashMap<String, String>();
          tskSrchFilter.put("Process Definition.Tasks.Task Name", taskName);
         
          tcResultSet tskSrchResSet = taskDefnOpsIntf.getTaskDetail(prcInstKey, tskSrchFilter);
         
          long retValue = 0L;
          if ((tskSrchResSet != null) && (tskSrchResSet.getTotalRowCount() != 0)){
            if(tskSrchResSet.getTotalRowCount() == 1){
              tskSrchResSet.goToRow(0);
              retValue = tskSrchResSet.getLongValue("Process Definition.Tasks.Key");
              System.out.println("retValue :: " + retValue);
            }else{
              System.out.println("Multiple Tasks found for Task Name :: " + taskName);
            }
          }else{
            System.out.println("No Task found for task Name :: " + taskName);
          }
          return retValue;
 }
   
 public List<String> getUsersFromFile(String sourceFile){
          System.out.println("Reading the data from CSV file :" + sourceFile);
          String userLogin = "";
          List<String> users = null;
          try{
            BufferedReader br = new BufferedReader(new FileReader(sourceFile));
            users = new ArrayList<String>();
             
            br.readLine();
            while(null != (userLogin = br.readLine())){
              users.add(userLogin.trim());
            }
            br.close();
          }catch (FileNotFoundException e){
            System.out.println("CSV file not found " + e.getMessage());
          }catch (IOException e){
            System.out.println("IO exception occured" + e.getMessage());
          }catch (Exception e){
            System.out.println("Error occured while reading file" + e.getMessage());
          }
          return users;
 }
   
 public static void main(String[] args){
        AddProcessTask obj = new AddProcessTask();
       
        //Users for which process task needs to be added
        String sourceFile = "D:/AddProcessTask/Users.csv";
       
        //Application Instance
        String appInstName = "ActiveDirectory";

        //Task Name
        String taskName = "Email Updated";

        //Account Status
        String accountStatus = "Provisioned";
       
        //get OIM Client
        obj.
getOIMConnection();
       
        //get list of users for which process task needs to be added
        List<String> userList = obj.getUsersFromFile(sourceFile);
       
        //add process task for users
        obj.addProcessTask(userList, appInstName, taskName, accountStatus);
   } 
}


Sample Users.csv file as shown below:


 
























Happy Learning!!!

Friday, 23 March 2018

OIM API - Code Snippet to Read OIM Notification Template Data.

public void getTemplateDataFromOIM(String templateName)
                            throws TemplateNotFoundException, MultipleTemplateException,
                            NotificationManagementException {
        final String logp = CN + " :: getTemplateDataFromOIM() - ";
        logger.log(Level.INFO, logp + "START");
        String subject = "";
        String body = "";
                  
        //get notification service
        NotificationService notificationService = Platform.getService(NotificationService.class);
       
        Locale defaultLocale = Locale.getDefault();
        NotificationTemplate temp = notificationService.lookupTemplate(templateName, defaultLocale);

        if (temp == null) {
            logger.severe(logp + "Template name not found : " + templateName);
            return;
        }

        subject = temp.getLocaltemplateCollection().get(defaultLocale.toString()).getSubject();
        logger.info(logp + "Email Subject is : " + subject);

        body = temp.getLocaltemplateCollection().get(defaultLocale.toString()).getLongmessage();
        logger.info(logp + "Email body is : " + body);

        logger.log(Level.INFO,logp + "END");
 }


Happy Learning!!!

OIM API - Code Snippet to Get Catalog UDF Value.

public String getCatalogUDFValue(String entityKey, String entityType, String udfName) throws CatalogException {
        OIMType type;
        String udfValue;
                  
        //get catalog service
        CatalogService catalogService = Platform.getService(CatalogService.class);
       
        if("ApplicationInstance".equalsIgnoreCase(entityType))
            type = OIMType.ApplicationInstance;
        else if("Entitlement".equalsIgnoreCase(entityType))
            type = OIMType.Entitlement;
        else if("Role".equalsIgnoreCase(entityType))
            type = OIMType.Role;
       
        Catalog catalog = catalogService.getCatalogItemDetails(null, entityKey, type, null);
        List<MetaData> metadata = catalog.getMetadata();

        for(MetaData metadataObject : metadata){
            MetaDataDefinition metdataDefinition = metadataObject.getMetaDataDefinition();           
            String columnName = metdataDefinition.getDbColumnName();
           
            if(columnName.equalsIgnoreCase(udfName)){
                udfValue = metadataObject.getValue();
                System.out.println(udfValue);
            }
        }
       return udfValue;
 }


Happy Learning!!!

OIM API - Code Snippet to Get Catalog Details for a Particular Request.

public void getCatalogDetailsForRequest(String requestID) throws RequestServiceException,
                                                                     NoRequestPermissionException,
                                                                     CatalogException {
        //get required services
        RequestService requestService = Platform.getService(RequestService.class);
        CatalogService catalogService = Platform
.getService(CatalogService.class);
       
        //get request object
        Request request = requestService.getBasicRequestData(requestID);
       
        List<Beneficiary> reqBeneficiaries = request.getBeneficiaries();
       
        for (Beneficiary beneficiary : reqBeneficiaries){
            List requestBeneficiaryEntityList = beneficiary.getTargetEntities();
            for(RequestBeneficiaryEntity requestBeneficiaryEntity : requestBeneficiaryEntityList){
                String entityKey = requestBeneficiaryEntity.getEntityKey();
                OIMType entityType = requestBeneficiaryEntity.getRequestEntityType();
               
                Catalog catalog = catalogService.getCatalogItemDetails(null, entityKey, entityType, null);
               
                System.out.println("Approver Role :: " + catalog.getApproverRole());
                System.out.println("Approver User :: " + catalog.getApproverUser());
                System.out.println("Category :: " + catalog.getCategoryName());
            }
        }
 }


Happy Learning!!!

OIM - Get Value of Given Parameter from Orchestration Map in Event Handler.

public String getParameterFrmOrchestration(HashMap<String, Serializable> userParamsMap, String param){
        final String logp = CN + " :: getParameterFrmOrchestration - ";
        LOGGER.log(Level.FINEST, logp + " START.");
        LOGGER.log(Level.INFO, logp + "Getting value of parameter: " + param);
        String paramValue = null;
        try {
            paramValue = (userParamsMap.get(param) instanceof ContextAware) ? (String)((ContextAware)userParamsMap.get(param)).getObjectValue() :
                    (String)userParamsMap.get(param);
            LOGGER.log(Level.INFO, logp + "Value of parameter '" + param + "' is : " + paramValue);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, logp + "Error Occured while fetching parameter value", e);
            e.printStackTrace();
        }
       
        LOGGER.log(Level.FINEST, logp + " END");
        return paramValue;
 }


Happy Learning!!!

OIM API - Code Snippet to Read ITResource Data for the given ITResource Name.

public Map<String, String> getITResourceMap(String itResName) {
        final String logp = CN + " :: getITResourceMap - ";
        LOGGER.debug(logp + "START");
        Map<String, String> itResourceMap = new HashMap<String, String>();
        Thor.API.Operations.tcITResourceInstanceOperationsIntf itResourceInstOps = null;
       
        if (null == itResName || itResName.isEmpty()) {
                return null;
        }
       
        LOGGER.info(logp + "IT resources Name :: " + itResName);
   
        try {
            HashMap<String, String> itMap = new HashMap<String, String>();
            itMap.put("IT Resources.Name", itResName);
            itResourceInstOps = Platform.getService(
tcITResourceInstanceOperationsIntf.class);
       
            tcResultSet itRS = itResourceInstOps.findITResourceInstances(itMap);
            LOGGER.info(logp + "Number of IT resources found for " + itResName + " = " + itRS.getRowCount());

            if (!itRS.isEmpty() && itRS.getRowCount() == 1) {
                itRS.goToRow(0);
                long itKey = itRS.getLongValue("IT Resource.Key");
                itRS = itResourceInstOps.getITResourceInstanceParameters(itKey);
                String name, value;
                for (int i = 0; i < itRS.getRowCount(); i++) {
                    itRS.goToRow(i);
                    name = itRS.getStringValue("IT Resources Type Parameter.Name");
                    value = itRS.getStringValue("IT Resources Type Parameter Value.Value");
                    itResourceMap.put(name, value);
                }
            }
        } catch (Exception e) {
            LOGGER.error("Exception while getting IT Resource details. " + e);
        } finally {
            if (null != itResourceInstOps) {
                itResourceInstOps.close();
                LOGGER.info(logp + "tcITResourceInstanceOperationsIntf instance closed successfully.");
            }
        }

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


Happy Learning!!!

OIM API - Code Snippet to 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;
    }


Happy Learning!!!