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





No comments:

Post a Comment