Saturday, 31 March 2018

OIM API - Code Snippet to get Scheduled Job Parameter Value for the given Parameter Name.

public String getScheduledJobParameter(String jobName, String paramName){
    final String logp = CN + " :: getScheduleJobParameter - ";
    LOGGER.debug(logp + "START");
   
    SchedulerService schedulerService = null;
    String value = "";

    try{
        //get scheduler service
        schedulerService = Platform.getService(SchedulerService.class);
       
        JobDetails jbDetails = schedulerService.getJobDetail(jobName);

        value = (String)jbDetails.getParams().get(paramName).getValue();
       
        LOGGER.info(logp + "Successfully obtained parameter value <" + value + ">" + "for job parameter <" + paramName + ">");
       
    } catch(Exception e){
        LOGGER.error(logp + "Exceptioin occurred while reading job parameter - " + paramName + " for job - " + jobName);
    }

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


Happy Learning!!!

OIM API - Update Role Details in OIM for the given Role Name.

 public void updateRole(String roleName){
        final String logp = CN + " :: updateRole - ";
        LOGGER.debug(logp + "START");

        //get role manager service
        RoleManager roleManager = Platform.getService(RoleManager.class);
       
        //get Role from OIM for the given Role Name
        Role role = getRole(roleName, roleManager);
       
        try{
            //Set Display Name
            role.setDisplayName("Role Display Name");

            //Set Description
            role.setDescription("Role Description");
                     
            //Update Role Details
            roleManager.modify(role);
           
            LOGGER.info(logp + "Successfully updated role details for - " + role);
           
        }catch(Exception e){
            LOGGER.error(logp + "Exception while updating Role in OIM - " + e, e);
        }

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



public Role getRole(String roleName, RoleManager roleManager){
        final String logp = CN + " :: getRole - ";
        LOGGER.debug(logp + "START");

        if (null == roleName || roleName.trim().length() == 0) {
                return null;
        }
        roleName = roleName.trim();

        Role role = null;
        try {
            SearchCriteria criteria = new SearchCriteria(RoleAttributeName.NAME.getId(), roleName, SearchCriteria.Operator.EQUAL);

            List<Role> roleList = roleManager.search(criteria, null, null);

            if(null == roleList || roleList.size() == 0){
                LOGGER.error(logp + "Role not found in OIM for role name - " + roleName);
            }else if(roleList.size() > 1){
                LOGGER.error(logp + "More than 1 role found in OIM for role name - " + roleName);
            } else {
                role = roleList.get(0);
                LOGGER.info(logp + "Successfully obtained role for role name " + roleName);
            }
        }catch(Exception e){
                LOGGER.error(logp + "Exception while fetching role  " + roleName + " - " + e, e);
        }

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


Happy Learning!!!

OIM API - Code Snippet to get Role from OIM for the given Role Name.

 public Role getRole(String roleName){
        final String logp = CN + " :: getRole - ";
        LOGGER.debug(logp + "START");

        if (null == roleName || roleName.trim().length() == 0) {
                return null;
        }
        roleName = roleName.trim();

        Role role = null;
        try {
            //get role manager service
            RoleManager roleManager = Platform.getService(RoleManager.class);
           
            SearchCriteria criteria = new SearchCriteria(RoleAttributeName.NAME.getId(), roleName, SearchCriteria.Operator.EQUAL);

            List<Role> roleList = roleManager.search(criteria, null, null);

            if(null == roleList || roleList.size() == 0){
                LOGGER.error(logp + "Role not found in OIM for role name - " + roleName);
            }else if(roleList.size() > 1){
                LOGGER.error(logp + "More than 1 role found in OIM for role name - " + roleName);
            } else {
                role = roleList.get(0);
                LOGGER.info(logp + "Successfully obtained role for role name " + roleName);
                LOGGER.info(logp + "Role Key : " + role.getEntityId());
                LOGGER.info(logp + "Role Display Name : " + role.getDisplayName());
            }
        }catch(Exception e){
                LOGGER.error(logp + "Exception while fetching role  " + roleName + " - " + e, e);
        }

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


Happy Learning!!!

OIM API - Update Application Instance Details in OIM for the given Application Instance Name.

 public void updateAppInstanceDetails(String appIntName){
        final String logp = CN + ":: updateAppInstanceDetails - ";
        LOGGER.debug(logp + "START");
       

        //get Application Instance Service
            ApplicationInstanceService appInstService = Platform.getService(ApplicationInstanceService.class);
  

      
        //get Application Instance from OIM for the given Application Instance Name
        ApplicationInstance appInst = getApplicationInstance(appIntName,
appInstService);

        try{
            //Set Display Name
            appInst.setDisplayName("Application Instance Display Name");

            //Set Description
            appInst.setDescription("Application Instance Description");
          
            //Update Application Instance Details
            appInstService.updateApplicationInstance(appInst);
           
            LOGGER.info(logp + "Successfully updated basic Application Instance details for - " + appInst);
        }catch(Exception e){
            LOGGER.error(logp + "Exception while updating ApplicationInstance in OIM - " + e, e);
        }

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



public ApplicationInstance getApplicationInstance(String appIntName, ApplicationInstanceService appInstService){
        final String logp = CN + "::
getApplicationInstance - ";
        LOGGER.debug(logp + "START");

        if(null == appIntName || appIntName.trim().length() == 0){
                LOGGER.error(logp + "Application Instance name is null or empty");
                return null;
        }
        appIntName = appIntName.trim();

        ApplicationInstance appInst = null;
        try{
            SearchCriteria criteria = new SearchCriteria(ApplicationInstance.APPINST_NAME, appIntName, SearchCriteria.Operator.EQUAL);
           
            List<ApplicationInstance> appInstList = appInstService.findApplicationInstance(criteria, null);

            if(appInstList.size() == 0 || appInstList.size() > 1) {
                LOGGER.error(logp + "Improper number of ApplicationInstance found in OIM for Application Instance name " + appIntName + " - " + appInstList.size());
            }else{
                appInst = appInstList.get(0);

                LOGGER.info(logp + "Successfully obtained ApplicationInstance - " + appInst);
            }
        }catch(Exception e) {
                LOGGER.error(logp + "Exception while fetching ApplicationInstance for Application Instance name " + appIntName + " - " + e, e);
        }

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


Happy Learning!!!

OIM API - Update Entitlement Details in OIM for the given Entitlement Name/Code.

  public void updateEntitlementDetails(String entName) {
        final String logp = CN + ":: updateEntitlementDetails - ";
        LOGGER.debug(logp + "START");
       
        try {

            //get entitlement service
            EntitlementService entServ = Platform.getService(EntitlementService.class);


             //get Entitlement from OIM for the given Entitlement Name
            Entitlement entitlement = getEntitlement(entName,
entServ);
           
            //Set Display Name
            entitlement.setDisplayName("Entitlement Display Name");

            //Set Description
            entitlement.setDescription("Entitlement Description");
           
            //Update Entitlement Details
            entitlementService.updateEntitlement(entitlement);
           
            LOGGER.info(logp + "Successfully updated basic entitlement details for - " + entitlement);
        }catch (Exception e) {
                LOGGER.error(logp + "Exception while updating entitlement in OIM - " + e, e);
        }

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



public Entitlement getEntitlement(String entName, EntitlementService entServ){
        final String logp = CN + ":: getEntitlementDetails - ";
        LOGGER.debug(logp + "START");

        if(null == entName || entName.trim().length() == 0){
                LOGGER.error(logp + "Entitmement name is null or empty");
                return null;
        }
        entName = entName.trim();

        Entitlement ent = null;
        try{
            SearchCriteria criteria = new SearchCriteria(Entitlement.ENTITLEMENT_NAME, entName, SearchCriteria.Operator.EQUAL);
           
            List<Entitlement> entList = entServ.findEntitlements(criteria, null);

            if (entList.size() == 0 || entList.size() > 1) {
                LOGGER.error(logp + "Improper number of entitlements found for entitlement name " + entName + " - " + entList.size());
            }else{
                    ent = entList.get(0);
                    LOGGER.info(logp + "Successfully obtained entitlement - " + ent);
            }
        }catch (Exception e){
                LOGGER.error(logp + "Exception while fetching entitlement for entitlement name " + entName + " - " + e, e);
        }

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



Happy Learning!!!

Thursday, 29 March 2018

OIM - SQL query to get all Catalog User Defined Fields(UDFs).

SELECT DB_COLUMN_NAME FROM CATALOG_METADATA_DEFINITION WHERE IS_UDF = 1;

OIM API - Code Snippet to get the Resource Object Name by the Application Instance Name.

 public String getResourceObjectName(String appInstName){
        final String logp = CN + " ::
getResourceObjectName() - ";
        logger.info(logp + "START");

        ApplicationInstanceService appService = Platform.getService(ApplicationInstanceService.class);
        ApplicationInstance appInst;
        try{
            appInst = appService.findApplicationInstanceByName(appInstName);
            String resourceObjectName = appInst.getObjectName();

            logger.info(logp + "Resource Object Name :" + resourceObjectName);
           
        }catch(ApplicationInstanceNotFoundException e){
            LOGGER.error(logp + "Exception while getting Resource Object Name " + e, e);
        }catch(GenericAppInstanceServiceException e){
            LOGGER.error(logp + "Exception while getting Resource Object Name " + e, e);
        }

        logger.info(logp + "END");
        return resourceObjectName;
 }


Happy Learning!!!

OIM API - Code Snippet to get the IT Resource Key by the IT Resource Name.

  public long getITResourceKeyByITResourceName(String itResName){
        final String logp = CN + " :: getITResourceKeyByITResourceName() - ";
        logger.info(logp + "START");
        long itResKey = 0L;
        tcITResourceInstanceOperationsIntf itResourceInstOps = null;
       
        if (null == itResName || itResName.isEmpty()){
            return itResKey;
        }
       
        try {
            HashMap<String, String> itMap = new HashMap<String, String>();
            itMap.put("IT Resources.Name", itResName);

            itResourceInstOps = Platform.getService(Thor.API.Operations.tcITResourceInstanceOperationsIntf.class);

            tcResultSet itRS = itResourceInstOps.findITResourceInstances(itMap);

            LOGGER.debug(logp + "Number of IT resources found for " + itResName + " = " + itRS.getRowCount());

            if (!itRS.isEmpty() && itRS.getRowCount() == 1) {
                itRS.goToRow(0);
                itResKey = itRS.getLongValue("IT Resource.Key");      
            }
        }catch(Exception e) {
            LOGGER.error(logp + "Exception while getting IT Resource Key for - " + itResName + " :: " + e, e);
        } finally {
            if (null != itResourceInstOps) {
                itResourceInstOps.close();
            }
        }
        logger.info(logp + "IT Resource Key : " + itResKey);
        logger.info(logp + "END");
        return itResKey;
  }


Happy Learning!!!

OIM API - Code Snippet to get ProcessInstanceKey by ApplicationInstanceName and UserKey.

  public String getProcessInstanceKey(String userKey, String appInstName){
       final String logp = CN + " :: getProcessInstanceKey - ";
       logger.info(logp + "START");

       ProvisioningService provServOps = Platform.getService(ProvisioningService.class);
      
       String procInstKey = null;
       List<Account> accountList = null;
       try{
           accountList = provServOps.getAccountsProvisionedToUser(userKey);
          
           for(Account account : accountList){
           if ((account.getAppInstance().getApplicationInstanceName().equalsIgnoreCase(appInstName)) &&
               ((account.getAccountStatus().equalsIgnoreCase("Provisioned")) ||
                account.getAccountStatus().equalsIgnoreCase("Enabled"))){
                   logger.info(logp + "Account is Provisioned/Enabled");
                   if((Account.ACCOUNT_TYPE.Primary).equals(accountprovisioned.getAccountType())){
                       logger.info(logp + "Account is Primary");
                       procInstKey = account.getProcessInstanceKey();


                       logger.info(logp + "procInstKey : " + procInstKey);
                   }
               }
           }
       }catch(Exception e){
           logger.error(logp + "Exception while getting IT Process Instance Key for - " + e, e);
       }
       logger.info(logp + "END");
       return procInstKey;
  }


Happy Learning!!!

Saturday, 24 March 2018

OIM API - Code Snippet to Set Display Name of User.

public void setDisplayNameOfUser(String userKey, String displayName){
        final String logp = CN + " :: setDisplayNameOfUser - ";
        LOGGER.log(Level.FINEST, logp + "START");
        HashMap<String, Object> modifyMap = new HashMap<String, Object>();
       
        //get user manager service
        UserManager usrService = Platform.getService(UserManager.class);
       
        //create display name map
        HashMap displayNameMap = new HashMap();
        displayNameMap.put("base", displayName);
        modifyMap.put(UserManagerConstants.AttributeName.DISPLAYNAME.getId(), displayNameMap);
       
        try{
            User newUser = new User(userKey, modifyMap);
            LOGGER.log(Level.INFO, logp + "User to update :: " + userKey);
            UserManagerResult result = usrService.modify(AttributeName.USER_KEY.getId(), userKey, newUser);
            LOGGER.log(Level.INFO, logp + "Operations Status :: " + result.getStatus());
        }catch(Exception e){
            LOGGER.log(Level.SEVERE, logp + "Exception occured :: " ,e.getMessage());
        }
        Logger.log(Level.FINEST, logp + "END");
 } 


Happy Learning!!!!

OIM API - Code Snippet to Set Manager of User.

public void setManagerOfUser(String userLogin, String userManagerLogin){
        final String logp = CN + " :: setManagerOfUser - ";
        LOGGER.log(Level.FINEST, logp + "START");
        LOGGER.log(Level.INFO, logp + "User Manager Login :: " + userManagerLogin);
        HashMap<String, Object> modifyMap = new HashMap<String, Object>();
       
        //get user manager service
        UserManager usrService = Platform.getService(UserManager.class);
       
        //get manager's user key
        Long userManagerKey = Long.valueOf(getUserKeyByUserLogin(userManagerLogin, usrService));
        modifyMap.put(UserManagerConstants.AttributeName.MANAGER_KEY.getId(), userManagerKey);

        //get user key of User for which manager needs to be set
        String userKey = getUserKeyByUserLogin(userLogin, usrService);
       
        try{
            User newUser = new User(userKey, modifyMap);
            LOGGER.log(Level.INFO, logp + "User to update :: " + userLogin);
            UserManagerResult result = usrService.modify(AttributeName.USER_KEY.getId(), userKey, newUser);
            LOGGER.log(Level.INFO, logp + "Operations Status :: " + result.getStatus());
        }catch(Exception e){
            LOGGER.log(Level.SEVERE, logp + "Exception occured :: " ,e);
        }
        Logger.log(Level.FINEST, logp + "END");
 }
  

      
public String getUserKeyByUserLogin(String userLogin, UserManager userService){
            HashSet<String> attrsToFetch = new HashSet<String>();
            attrsToFetch.add(UserManagerConstants.AttributeName.USER_KEY.getId());

            String usrKey = "";
            try{          
                User user = userService.getDetails(userLogin, attrsToFetch, true);
                usrKey = user.getEntityId();
            }catch(Exception e){
                e.printStackTrace();
            }
            return usrKey;
 }


Happy Learning!!!

OIM - How to get SOA Database Connection?

public void getSOADatabaseConnection(){
        Connection connection = null;
        DataSource soaDataSource = null;

        try {
            Context ctx = null;
            Hashtable ht = new Hashtable();
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
            ht.put(Context.PROVIDER_URL,"t3://<REPLACE_SOA_HOST_NAME>:<REPLACE_PORT>"); //eg- t3://10.22.34.56:8001
           
            ctx = new InitialContext(ht);
            soaDataSource = (javax.sql.DataSource)ctx.lookup("jdbc/SOADataSource");
            connection = soaDataSource.getConnection();
            System.out.println("Connected to SOA Database...");
        } catch(Exception e) {
            System.out.println("Exception occured while getting SOA DB connection " + e);
        }finally{
            if(null != connection){
                try{
                    connection.close();
                }catch(SQLException e){
                    System.out.println("Exception occured closing connection " + e);
                }
            } 
        }
 }


Happy Learning!!!

Code Snippet to Send Email Notification using Java Transport API.

public static void main(String[] args){
        final String username = "<SMTP Server User Name>";
        final String password = "<SMTP Server Password>";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "<SMTP Server Host Name>");
        props.put("mail.smtp.port", "<SMTP Server Port>"); //generally it is 25.

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                }
          });

        try{
            Message message = new MimeMessage(session);
           
            //set from email address
            message.setFrom(new InternetAddress("anandrajbadal@gmail.com"));
           
            //set TO Recipients
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("anandrajbadal@ymail.com"));
           
            //set CC Recipients
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("anandrajbadal@rediff.com"));
           
            //set subject
            message.setSubject("Test Mail");
           
            //set body
            message.setText("This is test email");
   
            Transport.send(message);
            System.out.println("Email sent successfully");
        }catch(MessagingException e){
            throw new RuntimeException(e);
        }
 }


Happy Learning!!!

OIM API - Code Snippet to get User Key by User Login.

public String getUserKeyByUserLogin(String userLogin){
        HashSet<String> attrsToFetch = new HashSet<String>();
        attrsToFetch.add(UserManagerConstants.AttributeName.USER_KEY.getId());

        String usrKey = "";
        try{     
            //get user manager service
            UserManager userService = Platform.getService(UserManager.class);
           
            User user = userService.getDetails(userLogin, attrsToFetch, true);
            usrKey = user.getEntityId();
        }catch(NoSuchUserException e){
            e.printStackTrace();
        }catch(UserLookupException e){
            e.printStackTrace();
        }catch(AccessDeniedException e){
            e.printStackTrace();
        }
        return usrKey;
 }


Happy Learning!!!

OIM API - Code Snippet to get Entitlement from OIM for the given Entitlement Name/Code.

 public Entitlement getEntitlement(String entName){
        final String logp = CN + ":: getEntitlementDetails - ";
        LOGGER.debug(logp + "START");

        if(null == entName || entName.trim().length() == 0){
                LOGGER.error(logp + "Entitmement name is null or empty");
                return null;
        }
        entName = entName.trim();

        Entitlement ent = null;
        try{
            SearchCriteria criteria = new SearchCriteria(Entitlement.ENTITLEMENT_NAME, entName, SearchCriteria.Operator.EQUAL);
           
            //get entitlement service
            EntitlementService entServ = Platform.getService(EntitlementService.class);
            List<Entitlement> entList = entServ.findEntitlements(criteria, null);

            if (entList.size() == 0 || entList.size() > 1) {
                LOGGER.error(logp + "Improper number of entitlements found for entitlement name " + entName + " - " + entList.size());
            }else{
                    ent = entList.get(0);
                    LOGGER.info(logp + "Successfully obtained entitlement - " + ent);
                    LOGGER.info(logp + "Entitlement Key - " + ent.getEntitlementKey());
                    LOGGER.info(logp + "Entitlement Display Name  - " + ent.getDisplayName());
                    LOGGER.info(logp + "IT Resource Key  - " + ent.getItResourceKey());
            }
        }catch (Exception e){
                LOGGER.error(logp + "Exception while fetching entitlement for entitlement name " + entName + " - " + e, e);
        }

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


Happy Learning!!!

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