Friday, 27 July 2018

Sending Notification to end user if the user gets locked in OIM

I created a post-process event handler for LOCK operation with Bulk operation method
Note* As per Oracle documentation for Lock and Unlock operations only bulk method works (for both bulk & non-bulk cases)

public BulkEventResult execute(long processId, long eventId, BulkOrchestration orchestration){
     
         HashMap<String, Serializable>[] orchParamArray = orchestration.getBulkParameters();
         String[] entityIds = orchestration.getTarget().getAllEntityId();
         int numUsers = entityIds.length;
         String userKey="",un="";
         dbbb gtn= new dbbb();
         gtn.connect2();
         for(int i = 0; i < numUsers; i++)
                         {
                             // Get USR_KEY of current user
                             userKey = entityIds[i];
                             un=gtn.getOIMUserInfo(userKey);
                             //Call the notification service here
                         }
         gtn.close();
         return new BulkEventResult();
}

Create a Plugin.xml

Create EventHandler.xml with operation="LOCK"

Put the EventHandler.xml in META-INF directory

Deploy the plugin!


Thursday, 20 April 2017

OAM Adaptive authentication Scheme mobile number Masking

By default Adaptive authentication scheme for second factor authentication mobile number (used for OTP) masking works for many numbers and masks them
but in some cases it does not mask some numbers
e.g.

+XX-XXX-XXXXXXX
+XX-XXXXXXXXXX

etc.

So we need to change the OOTB (PhoneMaskRegex) regular expression in the
Adaptive Authentication Module
&
Adaptive Authentication Scheme

\d{1,2}\D?\D?(\d{3})\D?\D?(\d{3})\D?(\d{2})\d{2}

\d{1,2} means any 2 digits can be in the beginning
\D? means it can be any Character
(\d{3}) means any 3 digits and these digits will be masked as *

Incase a character comes in the beginning OOTB RE does not handle it
So according to my situation to handle the above mentioned numbers I modified the OOTB RE

\D?\d{1,2}\D?\D?(\d{3})\D?\D?(\d{3})\D?(\d{2})\d{2,3}

Wednesday, 19 April 2017

Notify Management if the User is updated in OIM



import com.thortech.xl.crypto.tcCryptoUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import oracle.core.ojdl.logging.ODLLogger;
import static oracle.iam.identity.usermgmt.api.UserManagerConstants.AttributeName.MANAGER_KEY;
import static oracle.iam.identity.usermgmt.api.UserManagerConstants.AttributeName.USER_LOGIN;
import oracle.iam.identity.exception.AccessDeniedException;
import oracle.iam.identity.exception.NoSuchUserException;
import oracle.iam.identity.exception.UserLookupException;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.notification.api.NotificationService;
import oracle.iam.notification.vo.NotificationEvent;
import oracle.iam.platform.Platform;
import oracle.iam.platform.kernel.EventFailedException;
import oracle.iam.platform.kernel.OrchestrationEngine;
import oracle.iam.platform.kernel.spi.PostProcessHandler;
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 userModifyNotification implements PostProcessHandler{
   
    private ODLLogger logger = ODLLogger.getODLLogger("com.scb.oim.generateEmailID");
   
    /*
      This method is used to send Notification to user when User is updated using Self Service
 */
    
    public EventResult execute(long processId, long eventId, Orchestration orchestration) {
        String usrKey = null;
        logger.entering("Notification", "EventResult execute");
      
      
         String entityType = orchestration.getTarget().getType();
         EventResult result = new EventResult();
       
        if (!orchestration.getOperation().equals("MODIFY")) {
        usrKey = orchestration.getTarget().getEntityId();
        } else {
        OrchestrationEngine orchEngine = Platform.getService(OrchestrationEngine.class);
        usrKey = (String) orchEngine.getActionResult(processId);
        }
       
        try{
                         String templateName = "notifyuserdeleted";
                            NotificationService notService = Platform
                                            .getService(NotificationService.class);
                            NotificationEvent eventToSend = this
                                            .createNotificationEvent(templateName, "17381",usrKey);
                            notService.notify(eventToSend);
                           
                    }
                    catch(Exception e)
                    {
                        }
        logger.exiting("Notification", "ExecuteEvent");
               return new EventResult();
    }
   
   
    /*
     * This method is used to create the Notification Event using the Template Name and User Key
     */
    private NotificationEvent createNotificationEvent(String poTemplateName, String userKey,String userID) {
        logger.entering("Notification", "createNotificationEvent()");
        NotificationEvent event = null;
       
        try {
             String UserIDN=userID;
           
                event = new NotificationEvent();
                String[] receiverUserIds = getRecipientUserIds(userKey);
                event.setUserIds(receiverUserIds);
                event.setTemplateName(poTemplateName);
                event.setSender(null);
                logger.info("User ID: "+receiverUserIds.toString());
                logger.info("Template Name: "+poTemplateName);
                HashMap<String, Object> templateParams = new HashMap<String, Object>();
                templateParams.put("usr_key", UserIDN);
               
                event.setParams(templateParams);
                logger.exiting("Notification", "createNotificationEvent()");
        } catch (Exception e) {
                e.printStackTrace();
                logger.severe("Exception in createNotificationEvent()"+e.getMessage());
        }
        return event;
    }
    public BulkEventResult execute(long l, long l1,
                                   BulkOrchestration bulkOrchestration) {
       return null;
    }
   
    /**
      This method is used to fetch the UserID of the reciepient to whom the Notification needs to be sent
     */
    private String[] getRecipientUserIds(String userKey) throws NoSuchUserException, UserLookupException, AccessDeniedException {
        UserManager usrMgr = Platform.getService(UserManager.class);
        User user = null;
        String userId = null;
        Set<String> userRetAttrs = new HashSet<String>();
        userRetAttrs.add(MANAGER_KEY.getId());
        userRetAttrs.add(USER_LOGIN.getId());
        User manager = null;
        String managerId = null;
        String managerKey = null;
        Set<String> managerRetAttrs = new HashSet<String>();
        managerRetAttrs.add(USER_LOGIN.getId());
        user = usrMgr.getDetails(userKey, userRetAttrs, false);
        userId = user.getAttribute(USER_LOGIN.getId()).toString();
        List<String> userIds = new ArrayList<String>();
        userIds.add(userId);
        if (user.getAttribute(MANAGER_KEY.getId()) != null) {
                managerKey = user.getAttribute(MANAGER_KEY.getId()).toString();
                manager = usrMgr.getDetails(managerKey, managerRetAttrs, false);
                managerId = manager.getAttribute(USER_LOGIN.getId()).toString();
                //userIds.add(managerId);
        }
        String[] recipientIDs = userIds.toArray(new String[0]);
        return recipientIDs;
    }
     public boolean cancel(long l, long l1,
                          AbstractGenericOrchestration abstractGenericOrchestration) {
        return false;
    }
     public void initialize(HashMap<String, String> hashMap) {
    }
     public void compensate(long l, long l1,
                           AbstractGenericOrchestration abstractGenericOrchestration) {
    }
   
   
    
}




Deploy it in JAR file

Create a lib directory and put the JAR file in it

Create a Plugin.xml

Copy the below code in it

</oimplugins>  </plugins>    </plugin>    <plugin pluginclass="com.handler.iam.userModifyNotification" version="1.0" name="userModifyNotification">  <plugins pluginpoint="oracle.iam.platform.kernel.spi.EventHandler"><oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><?xml version="1.0" encoding="UTF-8"?>

Create EventHandler.xml

Copy the below code in it

</eventhandlers><action-handler class="com.handler.iam.userModifyNotification" entity-type="User" operation="MODIFY" name="userModifyNotification" stage="postprocess" order="1000"    sync="TRUE" /><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"><?xml version="1.0" encoding="UTF-8"?>

Put the EventHandler.xml in META-INF directory

Deploy the plugin!


Sunday, 12 March 2017

Custom Scheduler Job in OIM

In this post I will discuss how to create a custom scheduled job.


We will create a custom job to send email notification to the users who haven't yet registered their profiles in OAAM. Their status should be Active/Unlocked & enabled and they should not have their email field empty.



//Skip this if you are not going to send any email notification in the job

For that first create a custom event and a template corresponding to that event.

http://identitymanagementdeveloper.blogspot.com/2017/03/sending-notification-to-management-with.html

If you want send customized data in the template you can also create a custom resolver class as well.

http://identitymanagementdeveloper.blogspot.com/2017/03/create-custom-resolver-class-in-this.html




Create a new project in Jdeveloper with all the required jar files in class path


==========================================================================
package com.iam.custom;

import java.util.HashMap;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.notification.api.NotificationService;
import oracle.iam.notification.vo.NotificationEvent;
import oracle.iam.platform.Platform;
import oracle.iam.scheduler.vo.TaskSupport;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import oracle.core.ojdl.logging.ODLLogger;
import static oracle.iam.identity.usermgmt.api.UserManagerConstants.AttributeName.MANAGER_KEY;
import static oracle.iam.identity.usermgmt.api.UserManagerConstants.AttributeName.USER_LOGIN;
import oracle.iam.identity.exception.AccessDeniedException;
import oracle.iam.identity.exception.NoSuchUserException;
import oracle.iam.identity.exception.UserLookupException;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.notification.api.NotificationService;
import oracle.iam.notification.vo.NotificationEvent;
import oracle.iam.platform.Platform;
import oracle.iam.platform.kernel.spi.PostProcessHandler;
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;
import oracle.iam.upgrade.metadata.Params;

public class NotificationJob extends TaskSupport
{


//this functions get called on the job execution and you can perform any functionality in it
//I have first fetched a list of users keys using jdbc then extracted user ids by using //getRecipientUserIds then created a notification event using createNotificationEvent

    @Override
    public void execute(HashMap hm) throws Exception
    {
        GetUserName gun= new GetUserName();
        String ul[]=gun.getUserInfo();
            for (String s: ul) {          
                    //Do your stuff here
                    String templateName = "CustomNotification";
                    NotificationService notService = Platform
                                    .getService(NotificationService.class);
                    NotificationEvent eventToSend = this
                                    .createNotificationEvent(templateName, s);
                    notService.notify(eventToSend);
                }
        }
       
   
    private NotificationEvent createNotificationEvent(String poTemplateName, String userKey) {
        NotificationEvent event = null;
        try {
             String UserIDN=userKey;
           
                event = new NotificationEvent();
                String[] receiverUserIds = getRecipientUserIds(userKey);
                event.setUserIds(receiverUserIds);
                event.setTemplateName(poTemplateName);
                event.setSender(null);
                HashMap<String, Object> templateParams = new HashMap<String, Object>();
                templateParams.put("usr_key", UserIDN);
               
                event.setParams(templateParams);
        } catch (Exception e) {
                e.printStackTrace();
        }
        return event;
    }

    private String[] getRecipientUserIds(String userKey) throws NoSuchUserException, UserLookupException, AccessDeniedException {
        UserManager usrMgr = Platform.getService(UserManager.class);
        User user = null;
        String userId = null;
        Set<String> userRetAttrs = new HashSet<String>();
        userRetAttrs.add(MANAGER_KEY.getId());
        userRetAttrs.add(USER_LOGIN.getId());
        User manager = null;
        String managerId = null;
        String managerKey = null;
        Set<String> managerRetAttrs = new HashSet<String>();
        managerRetAttrs.add(USER_LOGIN.getId());
        user = usrMgr.getDetails(userKey, userRetAttrs, false);
        userId = user.getAttribute(USER_LOGIN.getId()).toString();
        List<String> userIds = new ArrayList<String>();
        userIds.add(userId);
        if (user.getAttribute(MANAGER_KEY.getId()) != null) {
                managerKey = user.getAttribute(MANAGER_KEY.getId()).toString();
                manager = usrMgr.getDetails(managerKey, managerRetAttrs, false);
                managerId = manager.getAttribute(USER_LOGIN.getId()).toString();
                userIds.add(managerId);
        }
        String[] recipientIDs = userIds.toArray(new String[0]);
        return recipientIDs;
    }

    @Override
    public HashMap getAttributes()
    {
        return null;
    }

    @Override
    public void setAttributes()
    {
        
    }
}


==========================================================================

In order to get Data from two different schemas OIM and OAAM
we need to make a nested query that will select all those users from OIM USR table who are ACTIVE, UNLOCKED, ENABLED and have a EMAIL address assigned to them and does not exist in OAAM schema tables which store information regarding registered profiles.

select USR_KEY  from OIG_OIM.USR where upper(OIG_OIM.USR.USR_LOGIN) not in (select upper(LOGIN_ID) from PROD_OAAM.vcrypt_users where PROD_OAAM.vcrypt_users.user_id in (select PROD_OAAM.v_user_qa.USER_ID from PROD_OAAM.v_user_qa)) AND OIG_OIM.USR.USR_DISABLED=0 AND OIG_OIM.USR.USR_LOCKED=0 AND OIG_OIM.USR.USR_EMAIL!='NULL' AND OIG_OIM.USR.USR_STATUS= 'Active'

We need a user who has access to both these schemas inorder to access them both!

==========================================================================
package com.iam.custom;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class GetUserName {
    public GetUserName() {
        super();
    }
    public  String[] getUserInfo() {
               
                int a=0;
               
                try {
                        // step1 load the driver class
                        Class.forName("oracle.jdbc.driver.OracleDriver");

                        // step2 create the connection object
                        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@IPADDRESSofDB:PORT:ServiceName", "User NAME",
                                        "Password");

                        // step3 create the statement object
                        Statement stmt = con.createStatement();

                        // step4 execute query
                        ResultSet rs = stmt.executeQuery("select count(USR_KEY) from OIG_OIM.USR where upper(OIG_OIM.USR.USR_LOGIN) not in (select upper(LOGIN_ID) from PROD_OAAM.vcrypt_users where PROD_OAAM.vcrypt_users.user_id in (select PROD_OAAM.v_user_qa.USER_ID from PROD_OAAM.v_user_qa)) AND OIG_OIM.USR.USR_DISABLED=0 AND OIG_OIM.USR.USR_LOCKED=0 AND OIG_OIM.USR.USR_EMAIL!='NULL' AND OIG_OIM.USR.USR_STATUS= 'Active'");

                        while (rs.next()) {

                                a = rs.getInt("COUNT(USR_KEY)");
                        }
                    System.out.println(a);

                        con.close();
                   

                } catch (Exception e) {
                        System.out.println(e);
                }
                String []ul = new String[a];
               
            try {
                    // step1 load the driver class
                    Class.forName("oracle.jdbc.driver.OracleDriver");

                    // step2 create the connection object
                   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@IPADDRESSofDB:PORT:ServiceName", "User NAME",
                                        "Password");

                    // step3 create the statement object
                    Statement stmt = con.createStatement();

                    // step4 execute query
                    ResultSet rs = stmt.executeQuery("select USR_KEY  from OIG_OIM.USR where upper(OIG_OIM.USR.USR_LOGIN) not in (select upper(LOGIN_ID) from PROD_OAAM.vcrypt_users where PROD_OAAM.vcrypt_users.user_id in (select PROD_OAAM.v_user_qa.USER_ID from PROD_OAAM.v_user_qa)) AND OIG_OIM.USR.USR_DISABLED=0 AND OIG_OIM.USR.USR_LOCKED=0 AND OIG_OIM.USR.USR_EMAIL!='NULL' AND OIG_OIM.USR.USR_STATUS= 'Active'");
                    int temp=0;
                    while (rs.next()) {

                            ul[temp] = rs.getString("USR_KEY");
                            temp++;
                    }

                    con.close();
               

            } catch (Exception e) {
                    System.out.println(e);
            }
          

                return ul;
        }
    }

==========================================================================

Now deploy it as a JAR file.

Create a file under the name metadata.xml and paste this code in it.




<?xml version="1.0" encoding="UTF-8"?>
<scheduledTasks xmlns="http://xmlns.oracle.com/oim/scheduler">
    <task>
        <name>Custom Notification Job</name>
        <class>com.iam.custom.NotificationJob</class>
        <description>Custom Notification Job</description>
        <retry>5</retry>
        <parameters>
        </parameters>
    </task>
</scheduledTasks>

Place metadata.xml inside META-INF directory and JAR file in lib directory

then create a plugin.xml and paste this code inside it



<?xml version="1.0" encoding="UTF-8"?>
<oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<plugins pluginpoint="oracle.iam.scheduler.vo.TaskSupport">
<plugin pluginclass= "com.iam.custom.NotificationJob"
version="1.1" name="CustomNotificationJob">
</plugin>
</plugins>
</oimplugins>

Now Register the plugin!


http://identitymanagementdeveloper.blogspot.com/2017/03/register-plugin-in-oim-11gr2.html

==========================================================================

Now go to SYS ADMIN console of OIM click on Scheduler under System Configuration.

Click on Actions -> Create

Give a name to the job

Now in the Task section click on the magnifying glass and search for (Custom Notification Job) or whatever name you gave it in metadata.xml file.

Enter rest of the desired data and click Apply and then run the job!


Saturday, 11 March 2017

Create a Custom Resolver in OIM



In this post I will create a custom resolver.

Whenever a template is called for sending email notification it resolves data  like ($User_ID) in the template and replaces them with the user information.

This functionality can be customized by creating a custom resolver class. I had a requirement that a password warning template should also send count down to expiry date
e.g. 3 days left in your password expiry.

To do this I created a custom resolver class and changed the previous event resolver class with mine in Metadata of OIM.




=========================================================================
package com.handler.iam;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 import static oracle.iam.identity.utils.Constants.USERID;
 import static oracle.iam.identity.utils.Constants.USERKEY;

import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.vo.Identity;
import oracle.iam.notification.api.NotificationService;
import oracle.iam.notification.impl.NotificationEventResolver;
import oracle.iam.notification.vo.NotificationAttribute;
import oracle.iam.platform.Platform;


public class CustomNotificationHandler implements NotificationEventResolver{

    public CustomNotificationHandler() {}


    public List<NotificationAttribute> getAvailableData(String eventType, Map<String, Object> map) {

        List<NotificationAttribute> list =
new ArrayList<NotificationAttribute>();
        NotificationAttribute na= new NotificationAttribute();
        na.setEntityName("DaysLeftinPWDExpiry");
        na.setName("DaysLeftinPWDExpiry");
        list.add(na);
        return list;
    }

    public HashMap<String, Object> getReplacedData(String eventType, Map<String, Object> eventParams) throws Exception {
       
        HashMap<String, Object> resolvedNotificationData = new HashMap<String, Object>();
        GetUserName gtn=new GetUserName();
        String UserName=gtn.getUserInfo(eventParams.get("usr_key").toString());
        resolvedNotificationData.put("User_Name", UserName);
        String Date1=gtn.getDate(eventParams.get("usr_key").toString());
        resolvedNotificationData.put("PwdExpDate", Date1);
        Date CurrentDate=java.util.Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date PwdExpDate=null;
        try{
        PwdExpDate= sdf.parse(Date1);
        //CurrentDate=sdf.parse(CurrentDate.toString());
        } catch (ParseException e) {
           System.out.println(e.toString());
        }
        long diff = PwdExpDate.getTime() - CurrentDate.getTime();//in Milli seconds
        long numOfDays = diff/(1000*60*60*24);
        resolvedNotificationData.put("DaysLeft", (numOfDays));
        return resolvedNotificationData;
    }
}
==========================================================================

package com.handler.iam;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class GetUserName {
    public GetUserName() {
        super();
    }
    public  String getUserInfo(String user_key) {
                String ul = null;
                try {
                        // step1 load the driver class
                        Class.forName("oracle.jdbc.driver.OracleDriver");
                        // step2 create the connection object
                        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@IPADDRESSofDB:PORT:ServiceName", "OIM SCHEMA NAME",
                                        "Password");
                        // step3 create the statement object
                        Statement stmt = con.createStatement();
                        // step4 execute query
                        ResultSet rs = stmt.executeQuery("select USR_LOGIN from OIG_OIM.USR where USR_KEY ='"+user_key+"'");
                        while (rs.next()) {
                                ul = rs.getString("USR_LOGIN");
                        }
                        con.close();
                } catch (Exception e) {
                        System.out.println(e);
                }
          
                return ul;
        }
    public  String getDate(String user_key) {
                String ul = null;
                try {
                        // step1 load the driver class
                        Class.forName("oracle.jdbc.driver.OracleDriver");
                        // step2 create the connection object
                        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@IPADDRESSofDB:PORT:ServiceName", "OIM SCHEMA NAME",
                                        "Password");
                        // step3 create the statement object
                        Statement stmt = con.createStatement();
                        // step4 execute query
                        ResultSet rs = stmt.executeQuery("select USR_PWD_EXPIRE_DATE from OIG_OIM.USR where USR_KEY ='"+user_key+"'");
                        while (rs.next()) {
                                ul = rs.getString("USR_PWD_EXPIRE_DATE");
                        }
                        con.close();
                } catch (Exception e) {
                        System.out.println(e);
                }
          
                return ul;
        }
}
==========================================================================

These 3 variable are Resolved:

$DaysLeft $User_Name $PwdExpDate

Now Create a plugin.xml

<?xml version="1.0" encoding="UTF-8"?>
<oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <plugins pluginpoint="oracle.iam.notification.impl.NotificationEventResolver">
    <plugin pluginclass="com.handler.iam.CustomNotificationHandler" version="2.1" name="Custom Notification Handler">
    </plugin>
  </plugins>
</oimplugins>

Register this Plugin & put resolver class in metadata event of your choice as com.handler.iam.CustomNotificationHandler


Sunday, 5 March 2017

Sending Notification to Management with UserID on successful user creation in OIM

In this post I will discuss the scenario where we want to send notification to management with User ID on successful account creation in OIM.


We have an out-of-box notification as well, where a mail is sent to user with User ID and password.


Now in our case only User ID will be sent to the management (can be any user in OIM). The same code can also be used to send other details as well.


1. First we need to create a Notification event that will be used by the template.


For that First we need to export the metadata from OIM


After exporting the Metadata got to the export directory

Metadata Export Directory.../metadata/iam-features-identity

Edit the IdentityNotificationEvent.xml

Add this tag in the XML file

<EventType name="Notify Management">
<StaticData>
<Attribute DataType="X2-Entity" EntityName="User" Name="Granted User"/>
</StaticData>
<Resolver class="oracle.iam.identity.notification.EndDateNotificationEventResolver">
<Param DataType="X2-Entity" EntityName="User" Name="usr_key"/>
</Resolver>
</EventType>

After that save the file and Import the updated metadata back into OIM



Now we have successfully created a new event.

2. Now we need to create a new template in OIM which will use this event.


Go to SYSADMIN console


Click on Notification


Now Click on Actions then Create to create a new template

Enter Template name and Select the  'Notify Management'  event from the available events list

Encoding: UTF-8

Message Subject: New Account has been created in OIM!

<html>
  <head></head>  
  <body>             
    <p> 
    New account has been created in OIM
    With Login_ID: $User_Login
    </p>
  </body>
</html>

Click on Save!

After that you need to purge the cache but we can do it after Registering the plugin as well.


3. Now we will write the custom PostProcessHandler code in Jdeveloper and create a custom plugin which will send the notification using the Notification template we created.


To use OIM API In Jdeveloper we need to get 2 jar files from OIM
oimclient.jar and ojdl.jar


Now lets get to work
In order to send notification to the management I created a account with their email ID in OIM and Extracted that user's 'USR_KEY' from USR table of OIM and entered it as a static value in the code.
Lets suppose that the 'USR_KEY' of the required user is 17381 


Create a new project in Jdeveloper add these 2 jar files in the
libraries & classpath

Sample code:





package com.handler.iam;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import oracle.core.ojdl.logging.ODLLogger;
import static oracle.iam.identity.usermgmt.api.UserManagerConstants.AttributeName.MANAGER_KEY;
import static oracle.iam.identity.usermgmt.api.UserManagerConstants.AttributeName.USER_LOGIN;

import oracle.iam.identity.exception.AccessDeniedException;
import oracle.iam.identity.exception.NoSuchUserException;
import oracle.iam.identity.exception.UserLookupException;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.notification.api.NotificationService;

import oracle.iam.notification.vo.NotificationEvent;
import oracle.iam.platform.Platform;
import oracle.iam.platform.kernel.spi.PostProcessHandler;
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 userCreationNotification implements PostProcessHandler{

    /*
    This method will send Notification to Admin User when User is created using OIM Self-Service Console

     */

public EventResult execute(long processId, long eventId, Orchestration orchestration) {
        try {
              String oprType = orchestration.getOperation();
              HashMap<String, Serializable> Params = orchestration.getParameters();
              Set<String> KeySet = Params.keySet();
              String usrLogin = null;
              String usrKey = null;
              for (String key : KeySet) {
               Serializable serializable = Params.get(key);
                if (key.equalsIgnoreCase("User Login")) {
                 usrLogin = serializable.toString();
                 UserManager usrMgr = Platform
                 .getService(UserManager.class);

                 User user = usrMgr.getDetails(usrLogin, null, true);
              usrKey = user.getEntityId(); // getAttribute("usr_key").toString();
                 String uid = user.getId();

                 //Enter your template Name here
                 String templateName = "Notify Management";

                 //Enter your Management USR_KEY here
                 String MUK="17381";
                 NotificationService notService = Platform
                    .getService(NotificationService.class);
                 NotificationEvent eventToSend = this
                    .createNotificationEvent(templateName, MUK , usrKey );
                 notService.notify(eventToSend);

                }
               }
               
        } catch (Exception e) {
                e.printStackTrace();
        }
        return new EventResult();
    }


    /*
    This method will be used to create the Notification Event using the Template Name and User Key
     */


private NotificationEvent createNotificationEvent(String poTemplateName, String userKey,String userID) {
   NotificationEvent event = null;
   try {
       String UserIDN=userID;
       event = new NotificationEvent();
       String[] receiverUserIds = getRecipientUserIds(userKey);
       event.setUserIds(receiverUserIds);
       event.setTemplateName(poTemplateName);
       event.setSender(null);
     HashMap<String, Object> templateParams = new HashMap<String, Object>();
       templateParams.put("usr_key", UserIDN);
       event.setParams(templateParams);
       } catch (Exception e) {
          e.printStackTrace();
       }
       return event;
 }


     /*
     This method will send Notification to Admin user when User is created using BulkUpload or Flat File
     */
public BulkEventResult execute(long l, long l1,BulkOrchestration bulkOrchestration) {
    try {
        String oprType = bulkOrchestration.getOperation();
       HashMap<String, Serializable>[] bulkParams = bulkOrchestration.getBulkParameters();
       for (HashMap<String, Serializable> bulkParam : bulkParams) {
          Set<String> bulkKeySet = bulkParam.keySet();
          String usrLogin = null;
          String usrKey = null;
          for (String key : bulkKeySet) {
             Serializable serializable = bulkParam.get(key);
             if (key.equalsIgnoreCase("User Login")) {
                usrLogin = serializable.toString();
                UserManager usrMgr = Platform
                .getService(UserManager.class);

                User user = usrMgr.getDetails(usrLogin, null, true);
                usrKey = user.getEntityId(); // getAttribute("usr_key").toString();
                String uid = user.getId();

                //Enter your template Name here
                String templateName = "Notify Management";
                //Enter your Management USR_KEY here
                String MUK="17381";
                NotificationService notService = Platform
                .getService(NotificationService.class);
                NotificationEvent eventToSend = this
                .createNotificationEvent(templateName, MUK ,usrKey);
                notService.notify(eventToSend);

               }
             }
          }
        } catch (Exception e) {
                e.printStackTrace();
        }
        return new BulkEventResult();
    }
   
    /*
      This method will fetch the UserID of the reciepient to whom the Notification needs to be sent in our case Management
        */
private String[] getRecipientUserIds(String userKey) throws NoSuchUserException, UserLookupException, AccessDeniedException {
   UserManager usrMgr = Platform.getService(UserManager.class);
   User user = null;
   String userId = null;
   Set<String> userRetAttrs = new HashSet<String>();
   userRetAttrs.add(MANAGER_KEY.getId());
   userRetAttrs.add(USER_LOGIN.getId());
   User manager = null;
   String managerId = null;
   String managerKey = null;
   Set<String> managerRetAttrs = new HashSet<String>();
   managerRetAttrs.add(USER_LOGIN.getId());
   user = usrMgr.getDetails(userKey, userRetAttrs, false);
   userId = user.getAttribute(USER_LOGIN.getId()).toString();
   List<String> userIds = new ArrayList<String>();
   userIds.add(userId);

   // if you want to send notification to the manger's manager as well use below code!
   /*if (user.getAttribute(MANAGER_KEY.getId()) != null) {
    managerKey = user.getAttribute(MANAGER_KEY.getId()).toString();
    manager = usrMgr.getDetails(managerKey, managerRetAttrs, false);
    managerId = manager.getAttribute(USER_LOGIN.getId()).toString();
    userIds.add(managerId);
  }*/
 String[] recipientIDs = userIds.toArray(new String[0]);
 return recipientIDs;
}


public boolean cancel(long l, long l1,
    AbstractGenericOrchestration abstractGenericOrchestration) {
     return false;
    }

    public void initialize(HashMap<String, String> hashMap) {
    }


    public void compensate(long l, long l1,
     AbstractGenericOrchestration abstractGenericOrchestration) {
    }


}



4. Now deploy this code to a JAR file and create a plugin


Create a folder NotifyManagemnt

Create these 2 folders inside
lib
META-INF

Now move the JAR file into lib folder
Now create a file in META-INF directory under the Name EventHandler.xml
and copy this code in that file

</eventhandlers><action-handler class="com.handler.iam.userCreationNotification" entity-type="User" operation="CREATE" name="Notify Management" stage="postprocess" order="FIRST" sync="TRUE"/><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"><?xml version="1.0" encoding="UTF-8"?>

Now Create another file plugin.xml in NotifyManagement Directory

and copy this code inside that file

<?xml version="1.0" encoding="UTF-8"?>
<oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <plugins pluginpoint="oracle.iam.platform.kernel.spi.EventHandler">
    <plugin pluginclass="com.handler.iam.userCreationNotification" version="1.0" name="userCreationNotification">
    </plugin>
  </plugins>
</oimplugins>

So far this is our directory Structure


NotifyManagement--|
                                  |
                                  |----------> lib ------------------------> plugin.jar
                                  |
                                  |----------> META-INF -------------> EventHandler.xml
                                  |
                                  |----------> plugin.xml


Put all these files in a ZIP folder and Register the Plugin in OIM