Sunday, February 12, 2012

OIM 11G API Usage

//Set the following vm arguments if you are executing in eclipse:
/*
-Djava.naming.provider.url=t3://hostname:port (for weblogic)
or
-Djava.naming.provider.url=jnp://hostname:port (for jboss)

Djava.security.auth.login.config=config\authwl.conf (for weblogic)
or
Djava.security.auth.login.config=config\auth.conf (for jboss)

-Djava.security.policy=config\xl.policy*/
Initializing the oimClient:

Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, providerURL);
            env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, OIMClient.WLS_CONTEXT_FACTORY);

            oimClient = new OIMClient(env);
            oimClient.login(userName, password.toCharArray());

//Getting the required service api's
usrMgrService = oimClient.getService(UserManager.class);
            notificationService = oimClient.getService(NotificationService.class);       
            roleMgrService = oimClient.getService(RoleManager.class);
            orgMgrService = oimClient.getService(OrganizationManager.class);

//Creating a user and user management
UserManager usrmanager=sample.getUsrMgrService();
            HashMap<String,Object> createUserMap=new HashMap<String, Object>();
            String userLogin="Testvish";
            createUserMap.put(UserManagerConstants.AttributeName.FIRSTNAME.getId(), "Testvish");
            createUserMap.put(UserManagerConstants.AttributeName.LASTNAME.getId(), "Testvish");
            createUserMap.put(UserManagerConstants.AttributeName.USER_LOGIN.getId(), "Testvish");
            createUserMap.put(UserManagerConstants.AttributeName.USERTYPE.getId(), "End-User");
            createUserMap.put(UserManagerConstants.AttributeName.EMPTYPE.getId(), "EMP");
            createUserMap.put(UserManagerConstants.AttributeName.PASSWORD.getId(), "vish@777");
            createUserMap.put(UserManagerConstants.AttributeName.DISPLAYNAME.getId(), "Testvish");
            createUserMap.put(UserManagerConstants.AttributeName.EMAIL.getId(), "Testvish@abc.com");
            createUserMap.put(UserManagerConstants.AttributeName.PHONE_NUMBER.getId(), "765454544");
            createUserMap.put("act_key", new Long("1"));
            User user=new User(userLogin,createUserMap);
            usrmanager.create(user);

//User Update
createUserMap.put("PHONE_NUMBER", "123456789");
            usrmanager.modify(new User(userLogin,createUserMap));

//Organization Create
String orgName="sampleOrg1";
            HashMap<String,Object> createOrgMap=new HashMap<String, Object>();
            createOrgMap.put("Organization Name", orgName);
            createOrgMap.put("Organization Customer Type", "Branch");
            Organization orgCreate = new Organization(orgName,createOrgMap);
            OrganizationManager orgManager=sample.getOrgMgrService();
            orgManager.create(orgCreate);

Pre-Process Event Handler to generate the Display Name in OIM 11G

public EventResult execute(long processId, long eventId, Orchestration orchestration) {

HashMap<String, Serializable> parameters = orchestration.getParameters();
HashMap<String, Object> mapAttrs = new HashMap<String, Object>();

String firstName = (String)parameters.get(UserManagerConstants.AttributeName.FIRSTNAME.getId());
String lastName = (String)parameters.get(UserManagerConstants.AttributeName.LASTNAME.getId());
mapAttrs.put("base", lastName" "firstName);

orchestration.addParameter("Display Name", mapAttrs);

return new EventResult();
}

Tuesday, February 7, 2012

Lotus Notes connection testing utility

The following piece of code can be used to test the connectivity with the lotus notes and also can be used to perform various operations:

Session _session=null;
         Session session=null;
         Database userDb;
         System.out.println("inside main");
         try {
             HashMap<String,String> credentialsMap=getHashMapFromProperties("./properties/LotusNotes.properties");
             String hostName=credentialsMap.get("HostName");
             System.out.println(hostName);
             String port=credentialsMap.get("PortNumber");
             System.out.println(port);
             String AdminID=credentialsMap.get("AdminID");
             System.out.println(AdminID);
             String AdminPwd=credentialsMap.get("AdminPassword");
             System.out.println(AdminPwd);
             String server=credentialsMap.get("Server");
             String database=credentialsMap.get("Database");
             System.out.println("Creating Notes Session");
             session=NotesFactory.createSession(hostName+":"+port,AdminID,AdminPwd);
             System.out.println("Session created successfully");
             userDb=session.getDatabase(server, database);
             System.out.println("Database loaded successfully");
             DocumentCollection collection=userDb.search("((form='Person')&(ShortName='"+arg[0]+"'))");
             int countDoc=collection.getCount();
             Document doc = collection.getFirstDocument();
.
.
.
-----
Reading the credentials from the properties file:

private static HashMap<String, String> getHashMapFromProperties(String filelocation){
          HashMap<String, String> hashMap = new HashMap<String, String>();
          String thisLine = null;   
          String DELIMITER="=";                     
   try {
               BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(new FileInputStream(filelocation)));
               while ((thisLine = bufferedReader.readLine()) != null) {
                    if(thisLine.trim().startsWith("#")) continue;
                    int indexOfDelimiter = thisLine.indexOf(DELIMITER);
                    hashMap.put(thisLine.substring(0, indexOfDelimiter), thisLine.substring(indexOfDelimiter + 1));
               }              
        } catch (FileNotFoundException e) {
               System.out.println("Exception Occurred while parsing " + filelocation+":"+e);
               System.exit(1);
          } catch (IOException e) {
               System.out.println("Exception Occurred while parsing " + filelocation+":"+e);  
               System.exit(1);
          }   
          return hashMap;
    }

Validation Handler in OIM 11G

This describes the usage of a validation handler used in validating the data entered as part of creating a request. This validation handler will be attached to the request dataset and which inturn will be invoked by OIM.

public class DataSetValidator implements oracle.iam.request.plugins.RequestDataValidator{

    public void validate(RequestData requestdata) throws InvalidRequestDataException {
        // TODO Auto-generated method stub

        // TODO Auto-generated method stub
        System.out.println("Entering the Data Validation Handler");
        List<Beneficiary> beneficiaries = null;    
        List<RequestBeneficiaryEntity> benEntities = null; 
            List<RequestBeneficiaryEntityAttribute> benAttrs = null;
            beneficiaries = requestdata.getBeneficiaries();
        if (beneficiaries != null && !beneficiaries.isEmpty()){
                     for (Beneficiary beneficiary : beneficiaries){
                   benEntities = beneficiary.getTargetEntities();
                       if (benEntities != null && benEntities.size() > 0){
                for (RequestBeneficiaryEntity benEntity : benEntities) {
                    System.out.println("Inside the For loop");
                    benAttrs = benEntity.getEntityData();
                    if (benAttrs != null && benAttrs.size() > 0){
                        System.out.println("Inside If");
                                    for (RequestBeneficiaryEntityAttribute benAttr : benAttrs){
                                        System.out.println("Inside the attributes For loop");
                                      System.out.println("Attribute Name is: "+benAttr.getName());
                                      System.out.println("Attribute Name is: "+benAttr.getValue());
                                        if(benAttr.hasChild()){
                            List <RequestBeneficiaryEntityAttribute> list = benAttr.getChildAttributes();
                                         Iterator iterator = list.iterator();
                                               while(iterator.hasNext()){
                                               RequestBeneficiaryEntityAttribute attribute =(RequestBeneficiaryEntityAttribute)iterator.next();
                                           System.out.println("GenericRequestValidator.validate() Name "+attribute.getName());
                                           System.out.println("GenericRequestValidator.validate()) Value "+attribute.getValue());
                                           }
                          }
                      }
                    }
                }
                }
                     }
        }else{
            System.out.println("RequestData is null");
        }
       
       
       
       
   
       
    }

After this we will have to package it and register this as a plugin in OIM. Later we will have to modify the request dataset xml as follows:

<DataSetValidator name="SampleValidator" classname="com.test.ad.DataSetValidator"/>

Note: We will have to export the dataset from the MDS and then modify it and then import the xml back. To export the dataset follow the steps below:
First, export the document by modifying the following values in
the weblogic.properties file and running the
weblogicExportMetadata.sh/weblogicExportMetadata.bat file:
wls_servername=oim server name, for example oim_server1
application_name=oim
metadata_to_loc=/scratch/data
metadata_files=/metadata/user/custom/EventHandlers.xml
The document will be exported to the /scratch/data/metadata/user/custom folder.
Under /scratch/data, if the folder structure /metadata/user/custom does not exist,
MDS will create it.

Importing into MDS:

To import the file into MDS, modify the following values in the
weblogic.properties file and run the
weblogicImportMetadata.sh/weblogicImportMetadata.bat file:
wls_servername=oim server name, for example oim_server1
application_name=oim
metadata_from_loc=/scratch/data

The above tag will be added as a child element under the request-data-set. So there will be only one dataset validator for one request dataset. Its a one to one.

Tuesday, January 24, 2012

Custom Event Handler in OIM 11G

Step 1:
 //The below code shows an example of implementing the PreProcessHandler. In the same way you can implement the other interfaces:
Pre-Process-- oracle.iam.platform.kernel.spi.PreProcessHandler
Post-Process-- oracle.iam.platform.kernel.spi.PostProcessHandler
Validation-- oracle.iam.platform.kernel.spi.ValidationHandler
Validation handler can be used to validate the data being entered while creating a user,role in OIM.
Writing a custom code to implement the actual logic:
Sample code:

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.thortech.util.logging.Logger;

import oracle.iam.platform.context.ContextAware;
import oracle.iam.platform.kernel.vo.AbstractGenericOrchestration;
import oracle.iam.platform.kernel.vo.BulkEventResult;
import oracle.iam.platform.kernel.vo.BulkOrchestration;
import oracle.iam.platform.kernel.vo.EventResult;
import oracle.iam.platform.kernel.vo.Orchestration;


public class GenerateUserID implements oracle.iam.platform.kernel.spi.PreProcessHandler{

    public boolean cancel(long l, long l1, AbstractGenericOrchestration abstractgenericorchestration) {
        // TODO Auto-generated method stub
        return false;
    }

    public void compensate(long l, long l1, AbstractGenericOrchestration abstractgenericorchestration) {
        // TODO Auto-generated method stub
       
    }

    public EventResult execute(long processID, long eventID, Orchestration orchestration) {
        // TODO Auto-generated method stub
        Logger logger=Logger.getLogger("CustomEventHandler");
        logger.debug("Entering the EventHandler");
        HashMap<String, Serializable> parameters = orchestration.getParameters();
        Set<String> keyset=parameters.keySet();
        Iterator<String> itr=keyset.iterator();
        while(itr.hasNext()){
            String attrName=itr.next();
            System.out.println("Attr Name is : "+attrName);
            System.out.println(parameters.get(attrName));
        }
        String middleName = getParamaterValue(parameters, "Middle Name");
        if (middleName==null||middleName.isEmpty()) {
            String firstName = getParamaterValue(parameters, "First Name");
            middleName = firstName.substring(1,3);
            orchestration.addParameter("Middle Name", middleName);
            }
        return new EventResult();
    }

    public BulkEventResult execute(long l, long l1, BulkOrchestration bulkorchestration) {
        // TODO Auto-generated method stub
        return null;
    }
   
    private String getParamaterValue(HashMap<String, Serializable> parameters,
            String key) {
            String value = (parameters.get(key) instanceof ContextAware)
            ? (String) ((ContextAware) parameters.get(key)).getObjectValue()
            : (String) parameters.get(key);
            return value;
            }

    public void initialize(HashMap<String, String> arg0) {
        // TODO Auto-generated method stub
       
    }

   

}

Step 2:
Create a plugin.xml file with the following contents:



<?xml version="1.0" encoding="UTF-8"?>
<oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oracle.com/schema/oim/plugin plugin.xsd">
<plugins pluginpoint="oracle.iam.platform.kernel.spi.EventHandler">
<plugin pluginclass=
"com.test.ad.GenerateUserID"
version="1.0"
name="SamplePreprocessExtension">
</plugin>
</plugins>
</oimplugins>

Step 3:

Creating a metadata xml.
Note: Make sure that the right namespace is given if you are using the latest version 11.1.1.5. This is not required if you are using older version 11.1.1.3.
EventHandlers.xml
<?xml version="1.0" encoding="UTF-8"?> 
<eventhandlers xmlns="http://www.oracle.com/schema/oim/platform/kernel" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oracle.com/schema/oim/platform/kernel orchestration-handlers.xsd">
<!-- Custom preprocess event handlers -->
<action-handler
class="com.test.ad.GenerateUserID"
entity-type="User"
operation="CREATE"
name="SamplePreprocessExtension"
stage="preprocess"
order="1000"
sync="TRUE"/>
</eventhandlers>

Step 4: Packaging
Package the contents in the following manner:

Folder Handler.zip if extracted should look like this:
lib[dir]
plugin.xml[file]

Note: The lib folder should containg the jar file which has the custom eventhandler implementation.

Step 5:
Register the plugin using the OIM_HOME/plugin-utility/pluginregistration.xml.
Run the following command:
ant -f pluginregistration.xml register
Give the complete path of the zip file like /app/Oracle/CustomPlugins/Handler.zip and make sure that the user has enough permissions.
Note: make sure that the ant path is exported to the path.

Step 6:
MDS import:

 Using the weblogicImportMetadata.sh/bat import the EventHandlers.xml.

Now validate the user create functionality as implemented by the eventhandler.