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!


No comments:

Post a Comment