Reject/Complete Orphan Or Pending SOA Tasks from OIM via WorkFlowService

package com.massiveGaze.provision;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import oracle.bpel.services.workflow.IWorkflowConstants;
import oracle.bpel.services.workflow.WorkflowException;
import oracle.bpel.services.workflow.client.IWorkflowServiceClient;
import oracle.bpel.services.workflow.client.IWorkflowServiceClientConstants;
import oracle.bpel.services.workflow.client.WorkflowServiceClientFactory;
import oracle.bpel.services.workflow.query.ITaskQueryService;
import oracle.bpel.services.workflow.repos.Column;
import oracle.bpel.services.workflow.repos.Predicate;
import oracle.bpel.services.workflow.repos.TableConstants;
import oracle.bpel.services.workflow.repos.table.WFTaskConstants;
import oracle.bpel.services.workflow.task.ITaskService;
import oracle.bpel.services.workflow.task.model.IdentityType;
import oracle.bpel.services.workflow.task.model.IdentityTypeImpl;
import oracle.bpel.services.workflow.task.model.Task;
import oracle.bpel.services.workflow.verification.IWorkflowContext;
import oracle.iam.platform.workflowservice.exception.IAMWorkflowException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.massiveGaze.connection.DataSource;
import com.thortech.xl.dataaccess.tcDataSet;
import com.thortech.xl.dataobj.PreparedStatementUtil;
import com.thortech.xl.dataobj.util.XLDatabase;
/*/
 * bpm-services.jar Needed to compile code
 */

public class RejectPendingSOATasks{
 private IWorkflowContext wfCtx = null;

   HashMap<IWorkflowServiceClientConstants.CONNECTION_PROPERTY, String > bpelprops = new HashMap<IWorkflowServiceClientConstants.CONNECTION_PROPERTY, String>();
     {     
     bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_PROVIDER_URL,"t3://host:8001/soa-infra");
     bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_CREDENTIALS,"weblogic1");
     bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_PRINCIPAL,"weblogic");
     bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
     }
   IWorkflowServiceClient  wfSvcClient =   WorkflowServiceClientFactory.getWorkflowServiceClient(WorkflowServiceClientFactory.REMOTE_CLIENT,bpelprops,null); 
      
  public static void main(String args[]) {
   RejectPendingSOATasks rejectPendingSOATasks = new RejectPendingSOATasks(); 
   Map<Object,Object> entAssgnData = rejectPendingSOATasks.getEntAssignKeys();
   rejectPendingSOATasks.cleanupPendingEntitlements(entAssgnData);  
    } 
  
  public Map<Object,Object> getEntAssignKeys(){
      Map<Object,Object> entAssignData = new HashMap<Object,Object>();
      List<String> accountKeys = new LinkedList<String>();
      List<String> entListKeys = new LinkedList<String>();
  try {
    Connection con = DataSource.getConnection();
    Statement stmt = con.createStatement();
   String query = "SELECT ENT_ASSIGN_KEY,ENT_LIST_KEY,OIU_KEY FROM ENT_ASSIGN ORDER BY 1 DESC ";
  
    ResultSet rs = stmt.executeQuery(query);
    while(rs.next()){
     entListKeys.add(rs.getLong("ENT_LIST_KEY")+"");
     accountKeys.add(rs.getLong("OIU_KEY")+"");
    }
  } catch (SQLException e) {   
   e.printStackTrace();
  }
   entAssignData.put(accountKeys,entListKeys);
  return entAssignData;
  }
  public Task getTaskDetailsByID(String taskId) throws IAMWorkflowException{
      try {       
        ITaskQueryService querySvc = wfSvcClient.getTaskQueryService();
           wfCtx = getAdminWorkflowContext(querySvc);
           Task task=querySvc.getTaskDetailsById(wfCtx,taskId);
          return task;           
      } catch(WorkflowException e) {
          throw new IAMWorkflowException(e);
      }
  } 
 private static HashMap<String,String> getPayloadValues(Element pElement) {
      HashMap<String,String> map = new HashMap<String,String>();
      NodeList nl = pElement.getChildNodes();
      if(nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
           String nodeName = nl.item(i).getNodeName();
            NodeList subList = nl.item(i).getChildNodes();
            if(subList != null && subList.getLength() > 0) {
                  String nodeValue = subList.item(0).getNodeValue();
                 // logger("Element is " + nodeName +
                   //                " with a value of " + nodeValue);
                  map.put(nodeName,nodeValue);
            }

        }
      }
        return map;
    }

 public void cleanupPendingEntitlements(Map<Object,Object> entAssgnData){   
   logger( " validatePendingEntitlements Method getting called with entAssgnKeys ->"+entAssgnData);
    try {           
     
     List<Task> listOfTasksFrmSOA  = getManualFulfilmentTasks(entAssgnData);
     if(listOfTasksFrmSOA!=null && listOfTasksFrmSOA.size() > 0){
        logger( " Size of listOfTasksFrmSOA -> "+listOfTasksFrmSOA.size());
         for (Task task : listOfTasksFrmSOA) {
             String taskId = task.getSystemAttributes().getTaskId();
             String title =  task.getTitle();
            logger(" task-id = " + taskId  + "   \n task-title = "+ title);               
             Task currentTask =   getTaskDetailsByID(taskId);
             Element payload = currentTask.getPayloadAsElement();
             HashMap<String,String> payloadValuesMap = getPayloadValues(payload);               
             String entityType = (payloadValuesMap.get("EntityType") != null) ? (String) payloadValuesMap.get("EntityType") :"";
             String provOperation=(payloadValuesMap.get("ProvisioningOperation") != null) ? (String) payloadValuesMap.get("ProvisioningOperation") :"";
            
             if("Entitlement".equalsIgnoreCase(entityType)){
              /*boolean recordInOIM = compareTaskWithEntAssignData(payloadValuesMap,entAssgnKeys);
             logger("Does value exist for this task in OIM ?? = "+ recordInOIM);
              if(recordInOIM) {*/
                    logger(" OIM Entitlement Data exist for the task : " + taskId);
                     boolean isAssignedToGroup = false;
                     String assignee = getAssignee(task);
                     if(task.getSystemAttributes().getAssigneeGroups() != null && task.getSystemAttributes().getAssigneeGroups().size()>0) {
                         isAssignedToGroup = true;
                     }
                     rejectTask(task, taskId, assignee, isAssignedToGroup);
                     logger("Done rejecting the task :"+ taskId);   
             // }
             }else {
              logger("Resulted SOA task is not of type Entitlement...!");
              }
         }                                
     }else{
        logger( " listOfTasksFrmSOA Is NULL, There were no Matching records found in SOA...!"); 
     }                                   
         
     }catch (Exception e){
        logger("validatePendingEntitlements :  RejectTask method returns exception " +e);          
     }
 }

    public void rejectTask(Task task, String taskId, String assginee, boolean isAssignedToGroup) throws Exception {     
        ITaskService taskSvc =  wfSvcClient.getTaskService();
        ITaskQueryService querySvc =  wfSvcClient.getTaskQueryService();
        IWorkflowContext adminWorkflowCtx= getAdminWorkflowContext(querySvc);
        wfCtx = querySvc.authenticateOnBehalfOf(adminWorkflowCtx, assginee);
        System.out.println("  task.getSystemAttributes().getTaskId()   ->   " +task.getSystemAttributes().getTaskId());
        System.out.println("  String taskId   ->   " +taskId);
        if(isAssignedToGroup) {
            taskSvc.acquireTask(wfCtx, task);
        }
        taskSvc.updateTaskOutcome(wfCtx, taskSvc.addComment(wfCtx, task.getSystemAttributes().getTaskId(), "Cleaning manual provisioniong task"),"REJECT");         
    } 
    
    private IWorkflowContext getAdminWorkflowContext(ITaskQueryService querySvc) throws WorkflowException {       
        IWorkflowContext adminCtx;
        String username = (String) bpelprops.get(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_PRINCIPAL);
        String password = (String) bpelprops.get(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_CREDENTIALS);
        adminCtx = querySvc.authenticate(username, password.toCharArray(), "jazn.com");
        return adminCtx;
    }
    private String getAssignee(Task task) throws Exception {
        String assignee = "";        
        List<IdentityTypeImpl> assignedUsers = (List<IdentityTypeImpl>)task.getSystemAttributes().getAssignees();
        
        if (assignedUsers != null && assignedUsers.size() > 0) {
            assignee = assignedUsers.get(0).getId();
            return assignee;
        }
        
        List<IdentityType> assignedGroups = task.getSystemAttributes().getAssigneeGroups();
        if (assignedGroups != null && assignedGroups.size() > 0) {
            String assingeeGroup = assignedGroups.get(0).getId();
            if(assingeeGroup != null && assingeeGroup.isEmpty() == false) {
             String queryToGetAsignee = "SELECT USR_LOGIN FROM USR,UGP,USG WHERE USR.USR_KEY =USG.USR_KEY AND UGP.UGP_KEY = USG.UGP_KEY AND USR.USR_STATUS='Active' " +
                                        "AND UGP.UGP_NAME  = ? ";
             try{                
                tcDataSet moQds = new tcDataSet();              
                PreparedStatementUtil pstmt = new PreparedStatementUtil();
                pstmt.setStatement(XLDatabase.getInstance(), queryToGetAsignee);       
                pstmt.setString(1, assingeeGroup);              
                pstmt.execute();
                moQds = pstmt.getDataSet();   
                    if(moQds.getRowCount()>0){
                        moQds.goToRow(0); 
                        assignee = moQds.getString("USR_LOGIN");
                    }
                }catch(Exception sqlExp){
                   logger( "getAssignee : Exception During Executing Query -> "+queryToGetAsignee + " with assingeeGroup -> "+assingeeGroup + " sqlExp -> "+sqlExp);
                }
        
            }
        }
        return assignee;
    }
   
    public List<Task> getManualFulfilmentTasks(Map<Object,Object> entAssgnData) throws IAMWorkflowException{       
        ITaskQueryService querySvc =  wfSvcClient.getTaskQueryService();

        try{
            wfCtx = getAdminWorkflowContext(querySvc);
            System.out.println( "Creating Predicate Object to filter only DisconnectedProvisioning tasks from SOA.");              
            Predicate compositenamePredicate = new Predicate(TableConstants.WFTASKMETADATA_NAMESPACE_COLUMN,Predicate.OP_CONTAINS, "DisconnectedProvisioning");
            // _.LOGGER.log(Level.FINER, "Adding Predicate Object to filter TASK_STATE_ASSIGNED OR TASK_STATE_INFO_REQUESTED from SOA.");
            Predicate predicate = new Predicate(Column.getColumn(WFTaskConstants.STATE_COLUMN), Predicate.OP_EQ, IWorkflowConstants.TASK_STATE_ASSIGNED);
            predicate.addClause(Predicate.OR, Column.getColumn(WFTaskConstants.STATE_COLUMN), Predicate.OP_EQ,IWorkflowConstants.TASK_STATE_INFO_REQUESTED);
            
            // _.LOGGER.log(Level.FINER,"Adding filter Object to TEXTATTRIBUTE COLUMNs from SOA.");
            Predicate textAttributePredicate =null;
                //For Loop Size will be always 1 which contains list objects accountKeys=OIU_KEY and entListKeys=ENT_LIST_KEY
                for (Map.Entry<Object, Object> entry : entAssgnData.entrySet()){ 
                        List accountKeys = (LinkedList)entry.getKey();
                        List entListKeys = (LinkedList)entry.getValue();                        
                        textAttributePredicate = new Predicate(Column.getColumn(WFTaskConstants.TEXTATTRIBUTE7_COLUMN), Predicate.OP_IN, accountKeys);
                        textAttributePredicate.addClause(Predicate.AND, Column.getColumn(WFTaskConstants.TEXTATTRIBUTE8_COLUMN), Predicate.OP_IN, entListKeys);
                        predicate = new Predicate(predicate, Predicate.AND, textAttributePredicate);
                    }
            
            compositenamePredicate = new Predicate(compositenamePredicate, Predicate.AND, predicate);
            
            System.out.println( "Preparing list query columns,which should exist in SOA result...!");
            List<String> queryColumns = new ArrayList<String>();
            queryColumns.add("TASKID");
            queryColumns.add("TASKNUMBER");
            queryColumns.add("TITLE");
            queryColumns.add("OUTCOME");
            queryColumns.add("STATE");
            queryColumns.add("ASSIGNEDDATE");
            queryColumns.add("ROOTTASKID");
            queryColumns.add("ASSIGNEES");
            queryColumns.add("ASSIGNEEGROUPS");
    
            List optionalInfo = new ArrayList();      
            optionalInfo.add("Comments"); 
            
            List<Task> listOfTasksFrmSOA= null;
            listOfTasksFrmSOA = querySvc.queryTasks(wfCtx, queryColumns, optionalInfo,ITaskQueryService.AssignmentFilter.ALL, null, compositenamePredicate,null, 0, 0);
          System.out.println( " Returning  List object listOfTasksFrmSOA with Task details.");
            return listOfTasksFrmSOA;
            
        } catch(WorkflowException e) {
            throw new IAMWorkflowException(e);
        }finally {
               System.out.println( "Restoring run as subject");              
                }
    }
    public static void logger(String logStatement){
     System.out.println("RejectPendingSOATasks  : -> " +logStatement);
    }
}

No comments:

Post a Comment

About OIM

Oracle Identity Management enables organizations to effectively manage the end - to - end life - cycle of user ide...

Popular Posts