Tuesday, 16 May 2017

Upload jar for ScduleTask or JavaTask in OIM 11gR2 PS3 using API

You can upload the ScheduleTask and JavaTask jar in OIM from your custom java applications. Here is the example of the same. similarly you also download, update and delete jar files from OIM database.




public void uploadJar() throws PlatformServiceException{
      
  PlatformUtilsService platformUtilsService = (PlatformUtilsService) oimClient.getService(PlatformUtilsService.class);
        JarElement jarElement = new JarElement();
        jarElement.setName("abcd.jar");
        jarElement.setPath("/tmp/abcd.jar");
        jarElement.setType("ScheduleTask");
       
        Set jarElementSet = new HashSet();
        jarElementSet.add(jarElement);
       
        platformUtilsService.uploadJars(jarElementSet );
        System.out.println("Finish uploading jar" );
    }

Thursday, 11 May 2017

Update OIM 11gR2 PS3 Schedule job parameter programatically using API.

We can update OIM schedule job parameter programmatically using available APIs. Here is the code sample.




 public void updateSchedulerParam(String jobName, String paramName, String newValue){
 
  SchedulerService schdulerService = (SchedulerService)oimClientObj.getService(SchedulerService.class);
 
  try {
  
   JobDetails jobDetails = schdulerService.getJobDetail(jobName);
   HashMap<String, JobParameter> schParam = jobDetails.getParams();
  
   for (Entry<String, JobParameter> entry : schParam.entrySet()) {
      
    String key = entry.getKey();
       JobParameter jobParam = entry.getValue();
       Serializable value = jobParam.getValue();
             
       System.out.println("Old key value pair: "+key+" = "+ value);
      
       if (key.equalsIgnoreCase(paramName)){
        value = newValue;
        System.out.println(value.toString());
        jobParam.setValue(value);
      
        System.out.println(jobParam.getValue());
        schParam.put(key, jobParam);
        break;
       }
   }
   jobDetails.setParams(schParam);
   schdulerService.updateJob(jobDetails);
   System.out.println("Updated successfully");
  
 } catch (Exception e) {
    e.printStackTrace();
 }
 }

Update OIM 11gR2 PS3 catalog attributes using API

In OIM, catalog default attributes can be easily updated by Catalog Sync schedule job. But if you add any custom attributes in the catalog, those field are very difficult to update using the Catalog Sync job.


You can use the below code snippet to update catalog default and custom attributes. While using this code in real implementation, use a CSV file with all the data and attaché the code in a schedule task.


 /**
  * This method update catalog form of specified entity
  * @param DBColumnName Catalog form field name
  * @param DBColumnValue Catalog form field value
  * @throws SchedulerException
  */

 private void updateCatalogDetailsValue(String DBColumnName, Object DBColumnValue) throws SchedulerException{
 
  oracle.iam.platform.utils.vo.OIMType oimtype = null;
 
  CatalogService catalogAPI = (CatalogService)oimClientObj.getService(CatalogService.class);
 
  System.out.println("ItemName::"+ItemName);
  System.out.println("ItemType::"+ItemType);

  try {
 
   //Set catalog entity type
   if(ItemType.equals("Entitlement")){
    oimtype = oracle.iam.platform.utils.vo.OIMType.Entitlement;
   }
   if(ItemType.equals("Role")){
    oimtype = oracle.iam.platform.utils.vo.OIMType.Role;
   }
   if(ItemType.equals("ApplicationInstance")){
    oimtype = oracle.iam.platform.utils.vo.OIMType.ApplicationInstance;
   }
  
   //Get catalog form of a specified entity
   Catalog catalog = catalogAPI.getCatalogItemDetails(null, ItemName, oimtype, null);
  
   System.out.println("Found Catalog item Display Name: "+catalog.getEntityDisplayName());
  
   //Set default catalog fields
   if(DBColumnName.equalsIgnoreCase("Catagory")){
   
    catalog.setCategoryName(String.valueOf(DBColumnValue));
   }else if(DBColumnName.equalsIgnoreCase("Audit Objective")){
   
    catalog.setAuditObjectives(String.valueOf(DBColumnValue));
   }else if(DBColumnName.equalsIgnoreCase("User Defined Tags")){
   
    catalog.setUserDefinedTags(String.valueOf(DBColumnValue));
   }else if(DBColumnName.equalsIgnoreCase("Certifiable")){
   
    catalog.setCertifiable(Boolean.valueOf(DBColumnValue.toString()));
   }else if(DBColumnName.equalsIgnoreCase("Approver User")){
   
    catalog.setApproverUserLogin(String.valueOf(DBColumnValue));
    catalog.setApproverUser(getUserKey(String.valueOf(DBColumnValue)));
   }else if(DBColumnName.equalsIgnoreCase("Approver Role")){
   
    catalog.setApproverRoleDisplayName(String.valueOf(DBColumnValue));
    catalog.setApproverRole(getRoleKey(String.valueOf(DBColumnValue)));
   }else if(DBColumnName.equalsIgnoreCase("Certifier User")){
   
    catalog.setCertifierUser(getUserKey(String.valueOf(DBColumnValue)));
    catalog.setCertifierUserLogin(String.valueOf(DBColumnValue));
   
   }else if(DBColumnName.equalsIgnoreCase("Certifier Role")){
   
    catalog.setCertifierRoleDisplayName(String.valueOf(DBColumnValue));
    catalog.setCertfierRole(getRoleKey(String.valueOf(DBColumnValue)));
   }else if(DBColumnName.equalsIgnoreCase("Fulfilment User")){
   
    catalog.setFulFillMentUser(getUserKey(String.valueOf(DBColumnValue)));
    catalog.setFulFillMentUserLogin(String.valueOf(DBColumnValue));
   }else if(DBColumnName.equalsIgnoreCase("Fulfilment Role")){
   
    catalog.setFulFillmentRoleDisplayName(String.valueOf(DBColumnValue));
    catalog.setFulFillMentRole(getRoleKey(String.valueOf(DBColumnValue)));
   }else if(DBColumnName.equalsIgnoreCase("Risk Level")){
   
    if(String.valueOf(DBColumnValue)== "High Risk")
     catalog.setItemRisk(7);
    else if(String.valueOf(DBColumnValue)== "Medium Risk")
     catalog.setItemRisk(5);
    else if(String.valueOf(DBColumnValue)== "Low Risk")
     catalog.setItemRisk(3);
    else
     System.out.println("Wrong Risk Value");
   }else{
   
    //Updating custom field
    List<MetaData> catalogMetaDataList = catalog.getMetadata();
    MetaData catalogMetaData = null;
    for(int j=0; j< catalogMetaDataList.size(); j++){
    
     catalogMetaData = catalogMetaDataList.get(j);
     MetaDataDefinition catalogMetaDataDef = catalogMetaData.getMetaDataDefinition();
    
     System.out.println(j+":::catalogMetaDataDef.getDisplayName():::::"+catalogMetaDataDef.getDisplayName());
    
     if(catalogMetaDataDef.getDisplayName().equalsIgnoreCase(DBColumnName)){
     
      catalogMetaData.setValue(String.valueOf(DBColumnValue));
      catalogMetaDataList.set(j, catalogMetaData);
      break;
     }
    }
   
    //Set catalog metadata
    catalog.setMetadata(catalogMetaDataList);
   
   }
   //Update catalog
   catalogAPI.updateCatalogItems(catalog);
  
  } catch (CatalogException e) {
  
   e.printStackTrace();
  
   if ((e.toString().indexOf("No Detail found for specified catalog item") > 0)){
    System.out.println("Ignore msg");
   
   }else{
   
    throw new Exception("ERROR: Catalog Exception, see server log and server log for more details ");
   }
  
  }
 }

Close OIM 11gR2 PS3 Identity Certification in bulk using API

closing identity certification from OIM identity console is possible by an administrator, but feasible for large number. Here is a code example of doing the same for bulk.

You can get the list of certification which are not completed yet from the OIM database, using below query

select CERT_ID, USER_ID from CERTD_USER where CERT_ID in (select ID from CERT_SERTS where CERT_STATE in ('17','2','1','11','12',13','14','15','16'))

the CERT_SATE numbers are defined as below inside OIM

STATE_EXPIRED : 4
STATE_COMPLETE : 3
STATE_FINAL_REVIEW : 17
STATE_IN_PROGRESS : 2
STATE_NEW : 1
STATE_PHASE_1 : 11
STATE_PHASE_1_D : 12
STATE_PHASE_1_V : 13
STATE_PHASE_2 : 14
STATE_PHASE_2_D : 15
STATE_PHASE_2_V : 16

You can use the below code snippets to close all the open certification tasks.

/**
  *
  * @param cert_id: certification id. available in CERTD_USER table
  * @param userEntityId: User id for the certification which are pending. available in CERTD_USER.
  * @throws Exception
  */

 public void closeCertification(long cert_id,String userEntityId) throws Exception{
  
   CertificationService certificationService = (CertificationService)oimClient.getService(CertificationService.class);
    char[] oimAdminPassword = "Welcome1".toCharArray(); //Xelsysadm password
    
   List<Long> userEntityIds = new ArrayList<Long>();
   userEntityIds.add(Long.valueOf(userEntityId));
  
   
//get the certification instance from cert id
   CertificationInstance certInstance = certificationService.loadCertification(cert_id,null);
   System.out.println("Status : "+certInstance.getStatus());
   System.out.println("STATE_EXPIRED : "+CertificationConstants.STATE_EXPIRED);
   System.out.println("STATE_COMPLETE : "+CertificationConstants.STATE_COMPLETE);
  
 
  //get the different status level
   int status = certInstance.getStatus();
   int complete = CertificationConstants.STATE_COMPLETE;
   int expired = CertificationConstants.STATE_EXPIRED;
  
  
 //Checking the current status of the certification instance.
   if (status==complete) {
   
    System.out.println("certification already completed : "+cert_id);
   }else if(status==expired){
    System.out.println("certification already completed : "+cert_id);
   }  
   else{
   
    
//Certifying user of the cert instance with cancel comment
    certificationService.certifyUsers(cert_id, null, userEntityIds, CertificationConstants.STATUS_ABSTAIN, "Canceled due migration");
    certificationService.certifyRemainingUserContent(cert_id, null, userEntityIds, "Canceled due migration");
   
    if ( certificationService.canBeCompleted(cert_id, null) ) {
    
   
  //completing the certification.
     certificationService.completeCertification(cert_id, null, oimAdminPassword);
     System.out.println("Certification Completed successfully : "+cert_id);
    }else{
     System.out.println("Certification not Completed yet : "+cert_id+" , "+certInstance.getPercentComplete()+"% completed");
    }
   }
   

Assign and Revoke OIM Admin roles using API

OIM has several admin roles, which are under the scope of some organizations. in PS3 there is a separate application for managing admin roles, but in the older version this operation was incorporated under organization's life cycle.

Here are the API examples of managing Admin role life cycle like assigning or revoke. This API will work in all the OIM 11gR2 versions including PS3.

 /**
  * Assigning OIM Admin role to a user.
  * @param Userid
  * @param adminRoleName
  */

 public void assignAdminRole(String Userid, String adminRoleName){
 
  try {
  
  
 /**
    * initialize API and get the details of a specified admin role
    */

   AdminRoleService admRoleAPI = (AdminRoleService)oimClient.getService(AdminRoleService.class);
   AdminRole admRole = admRoleAPI.getAdminRole(adminRoleName);
  
   
//Print some details.
   System.out.println("Scope ::"+admRole.isScoped());
   System.out.println("Role Description ::"+admRole.getRoleDescription());
   System.out.println("Role Description ::"+admRole.getRoleId());
  
   //Create a new membership object.
   AdminRoleMembership admMembership = new  AdminRoleMembership();
   admMembership.setAdminRole(admRole);
   admMembership.setUserId(getUserKey(Userid));
  
   
/**
    * Every Admin role scoped under some organization (or organizations).
    * Assigning any admin role you need to set the scope id.
    */

   AdminRoleVO adminRoleVo = admRoleAPI.getAdminRoleVO(String.valueOf(admRole.getRoleId()));
   List<AdminRoleRuleScope> scopes = adminRoleVo.getAdminRoleRuleScopes();
   AdminRoleRuleScope scope = scopes.get(0);
   System.out.println("Admin Role In Scope Organization: "+scope.getInScopeOfOrganizationName()); //printing the organization name
   
     
   
/**
    * If the admin role is not scoped then set the scope id for SYSTEM ADMINISTRATOR organization
    * which is generally 3.  
    */
 
  if (admRole.isScoped()){
    
    admMembership.setScopeId(getOrgKey(scope.getInScopeOfOrganizationName()));
    
   }else{
    
    admMembership.setScopeId("3");
   }
   
    System.out.println("new set Scope ::"+admMembership.getScopeId());
    AdminRoleMembership newMemberShip = admRoleAPI.addAdminRoleMembership(admMembership);
    System.out.println("Admin Role Successfully Assigned to the User: "+Userid+" Key: "+newMemberShip.getUserId());
   
  
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.getMessage();
  }
 
 
 }

 
/**
  * Revok an Admin Role from user.
  * @param Userid
  * @param adminRoleName
  */

 public void revokeAdminRole(String Userid, String adminRoleName){
 
  AdminRoleService admRoleAPI = (AdminRoleService)oimClient.getService(AdminRoleService.class);
  List<String> adminRoles = new ArrayList();
  adminRoles.add(adminRoleName);
 
 
 /**
   * Get the user and admin role membership object.
   */

  List<AdminRoleMembership> adminMemberShipList = admRoleAPI.listMembershipsForUserByRoleName(getUserKey(Userid), adminRoles);
  AdminRoleMembership adminMemberShip = adminMemberShipList.get(0);
 
  
//revoke admin role.
  boolean status = admRoleAPI.removeAdminRoleMembership(adminMemberShip);
  System.out.println("Admin Role Successfully revoke from User: "+Userid+" Status: "+status);
 }


 
 /**
  * get user key from given username
  * @param userid
  * @return Userkey
  */

 private String getUserKey(String userid){
 
  String key = "";
  UserManager userAPI = (UserManager)oimClient.getService(UserManager.class);
  java.util.Set retAttrs = new HashSet();
  retAttrs.add(UserManagerConstants.AttributeName.USER_KEY.getId());
 
  User user;
  try {
   user = userAPI.getDetails(UserManagerConstants.AttributeName.USER_LOGIN.getId(), userid, retAttrs);
   key = user.getId();
  } catch (NoSuchUserException e) {
    e.printStackTrace();
  } catch (UserLookupException e) {
   e.printStackTrace();
  } catch (SearchKeyNotUniqueException e) {
   e.printStackTrace();
  } catch (AccessDeniedException e) {
     e.printStackTrace();
  }
  return key;
 }

 
 /**
  * get organization Key from a given Org name
  * @param orgName
  * @return OrgKey
  */

 private String getOrgKey(String orgName){
 
  String key = "";
  OrganizationManager orgAPI = (OrganizationManager)oimClient.getService(OrganizationManager.class);
  java.util.Set retAttrs = new HashSet();
  retAttrs.add(OrganizationManagerConstants.AttributeName.ID_FIELD.getId());
 
  try {
   Organization org = orgAPI.getDetails(OrganizationManagerConstants.AttributeName.ORG_NAME.getId(), orgName, retAttrs);
   key = String.valueOf(org.getAttribute("act_key"));
  
  } catch (SearchKeyNotUniqueException e) {
      e.printStackTrace();
  } catch (OrganizationManagerException e) {
    e.printStackTrace();
  } catch (AccessDeniedException e) {
    e.printStackTrace();
  }
 
  return key;
 }

Monday, 8 May 2017

Add a new page in OIM 11gR2 PS3 (With ADF Task Flow)

Implementing OIM in an organization doesn't fulfill all the requirements. Some time we need to do lot of customization to meet customer's expectations. The good thing about OIM is, you can customize the functionalities and User Interface as per your own requirements. Even you can add a complete new page to define your own functionalities.. In this post I am going to describe the basic steps to add a new page in OIM 11gR2 PS3.

Adding a new page in OIM is not like adding a new html or jsp page. OIM only support ADF task flow to show its contents, and the functionalities of this page will be executing inside OIM engine. if you observe the pages in OIM while opening, you can find the pages are opening in a new internal tab where browser url is fixed.


All this pages are nothing but ADF task flow. We can create our own task flow in ADF and merge it to OIM identity console home page.

1. first open the JDeveloper (I am using 11.1.1.6).
2. Create a new Fusion Web Application project.

3. click Next
4. The model project details appeared. Click Next

5. Click Next.
6. View controller project details appeared. Click Next.
7. Click Finish to create the project
8. once the project is created it will looks like the above image.
9. Now we have to create a new task flow in this project. Right click on the ViewController project and click on New
10. select the JSF from the left and select ADF Task Flow from the right.


11. click ok
12. Provide the name of the task flow and append "\oracle\iam\ui\custom" at the directory link after WEB-INF. Otherwise OIM will be unable to recognize the task flow. once done click on Ok to create the task flow.

13. Now open the task flow test-flow.xml,  drag the view components from the components pallet into the task flow page. Give a name like TestPage
14. Every view components you drag into this task flow page will be created as a fragment page. To create the fragment of this view component, double click on it.
15. It will ask you to create jsff page for that view components. provide a name (recommended to keep the default: TestPage.jsff) and click on Ok. It will create a .jsff page under Web Component.

16. Now open the TestPage.jsff. Drag the "Output text" component from the Source Elements (from right side panel) into the jsff page. Change the content of the text "This is the test task flow page in OIM PS3".


17. Drag a spacer component and another Output Text element into this jsff page.


18. Now click on the source table of the TestPage.jsff. Change the value of the last output text added as below.

value="#{oimcontext.currentUser['User Login']}"


Note: "#{oimcontext.currentUser['User Login']}"  is the EL (Expression Language) to display the currently logged in user's username. As we are embedding this task flow inside OIM identity console page, so we can use all the OIM's default ELs in this project.

19. Click on Save button to save the project.
20. The basic task flow project is ready. Now we have to create a new deployment profile for this project to build ADF library jar. OIM will read this task flow project as an added UI customization, and all UI customization in OIM required ADF Library Jar. other format will not work.

21. Right click on the ViewController project and click on New. Select Deployment Profile from left and ADF Library Jar from right and click Ok.


22. Click Ok.


23. Provide the jar name (recommendation is to keep the default). it should always start with adflib. Once done, click Ok.


24. When it will ask for the model project dependencies, click on Ok.


 25. In the Deployment page you can find the default WAR is also present with the newly added adf lib. Remove the WAR profile and keep only the ADF Lib Jar.


26. After removal click on Ok. Save the project and deploy the project by Right click on ViewController -> Deploy -> adflibOIMTF1


27. click Next

28. Click Next


29. Click on Finish to create the jar.


30. The message window will display the successful compilation of the project. It also display the path where the jar file is created.


31. Now we have to implement this jar file into OIM and link this task flow into OIM home page.
32. Login to OIM server using FTP, and copy the oracle.iam.ui.custom-dev-starter-pack.war  from [OIM_HOME]/servers/apps to your desktop.

33. Copy the adflibOIMTF1.jar to oracle.iam.ui.custom-dev-starter-pack.war /WEB-INF/lib



34. replace the old oracle.iam.ui.custom-dev-starter-pack.war file with the new one, back to the same location.

35. Restart the OIM server.

36. Open the OIM PS3 identity console. and create a new sandbox.
37. From the home page click on Customize.
38. All the OIM PS3 tiles are arranged in table manner. The entire page is a table. 1 tile box is a Colum of a row of the table. Each row can hold 4 columns (means 4 tiles). So if we need to add a new tile, then we have to select the row where new column can be added and add a new column on it.
if any row is not have space to hold columns the create a new row.

37. In this case I selected the 2nd row and added a new cell. click on the row and click on Add (+) button.


38. Now select Web Components.


39. Now add a new grid cell.



40. Now select the Grid cell and click on Add (+) button


41. From the same location select and Add Dashboard Tile.


42. Close the web composer of OIM. You can see the new tile is added with default name. Do not change any details of the tile from the OIM Web Composer.


43. Export the sandbox.

44. Open the sandbox zip and edit the oracle\iam\ui\homepage\home\pages\mdssys\cust\site\site\self-service-home.jsff as below. Just add the highlighted details into the page.


45. Save the page and copy it on to the sandbox.
46. Import the sandbox into OIM and make it active.
47. Go to the Home page of identity console and you can see the modifies tile.


48. Click on the tile and you can see a new page opened.


49. This way you can add new page in OIM.

In my next blog I will discuss, how to embed functionalities onto the newly added page, where task flow page will be integrated with managed bean, and managed bean will contains OIM APIs. 

Sunday, 7 May 2017

Creating Certificate store using java.

Using java you can create any type of certificate store. In the below example, I have created a JKS certificate store using sun.security.tools.KeyTool  API.

import java.io.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import sun.security.tools.KeyTool;

public class CreateCert {
    public static void main(String[] args) throws Exception {
        String FILE= [JKS FILE LOCATION];
        new File(FILE).delete();
        KeyTool.main(("-debug -genkeypair -keystore " + FILE + " -alias a -dname cn=[YOUR_NAME] -storepass [PASSWORD]"+ " -keypass changeit -keyalg rsa").split(" "));
        System.out.println("done");
        KeyStore ks=KeyStore.getInstance("JKS");
        System.out.println(ks.getType());
    }
}



Change the following parameter with your own values

[JKS FILE LOCATION] = path of the jks file  ex. "C://Test.jks"
[YOUR_NAME] = Your full name as JKS cn.
[PASSWORD] = Password of your JKS file.

Run the code. Your JKS will be created in the specified location.

Followers

OIM API for adding process task and retry failed task

 In this blog you can find how to add new process task and retry any failed/rejected tasks using API. Adding new process task: /************...