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


  1. package com.oimacademy.provision;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.LinkedList;
  9. import java.util.List;
  10. import java.util.Map;
  11. import oracle.bpel.services.workflow.IWorkflowConstants;
  12. import oracle.bpel.services.workflow.WorkflowException;
  13. import oracle.bpel.services.workflow.client.IWorkflowServiceClient;
  14. import oracle.bpel.services.workflow.client.IWorkflowServiceClientConstants;
  15. import oracle.bpel.services.workflow.client.WorkflowServiceClientFactory;
  16. import oracle.bpel.services.workflow.query.ITaskQueryService;
  17. import oracle.bpel.services.workflow.repos.Column;
  18. import oracle.bpel.services.workflow.repos.Predicate;
  19. import oracle.bpel.services.workflow.repos.TableConstants;
  20. import oracle.bpel.services.workflow.repos.table.WFTaskConstants;
  21. import oracle.bpel.services.workflow.task.ITaskService;
  22. import oracle.bpel.services.workflow.task.model.IdentityType;
  23. import oracle.bpel.services.workflow.task.model.IdentityTypeImpl;
  24. import oracle.bpel.services.workflow.task.model.Task;
  25. import oracle.bpel.services.workflow.verification.IWorkflowContext;
  26. import oracle.iam.platform.workflowservice.exception.IAMWorkflowException;
  27. import org.w3c.dom.Element;
  28. import org.w3c.dom.NodeList;
  29. import com.oimacademy.connection.DataSource;
  30. import com.thortech.xl.dataaccess.tcDataSet;
  31. import com.thortech.xl.dataobj.PreparedStatementUtil;
  32. import com.thortech.xl.dataobj.util.XLDatabase;
  33. /*/
  34.  * bpm-services.jar Needed to compile code
  35.  */
  36. public class RejectPendingSOATasks{
  37.  private IWorkflowContext wfCtx = null;
  38.    HashMap<IWorkflowServiceClientConstants.CONNECTION_PROPERTY, String > bpelprops = new HashMap<IWorkflowServiceClientConstants.CONNECTION_PROPERTY, String>();
  39.      {     
  40.      bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_PROVIDER_URL,"t3://host:8001/soa-infra");
  41.      bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_CREDENTIALS,"weblogic1");
  42.      bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_PRINCIPAL,"weblogic");
  43.      bpelprops.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
  44.      }
  45.    IWorkflowServiceClient  wfSvcClient =   WorkflowServiceClientFactory.getWorkflowServiceClient(WorkflowServiceClientFactory.REMOTE_CLIENT,bpelprops,null); 
  46.     public static void main(String args[]) {
  47.    RejectPendingSOATasks rejectPendingSOATasks = new RejectPendingSOATasks(); 
  48.    Map<Object,Object> entAssgnData = rejectPendingSOATasks.getEntAssignKeys();
  49.    rejectPendingSOATasks.cleanupPendingEntitlements(entAssgnData);  
  50.     }   
  51.   public Map<Object,Object> getEntAssignKeys(){
  52.       Map<Object,Object> entAssignData = new HashMap<Object,Object>();
  53.       List<String> accountKeys = new LinkedList<String>();
  54.       List<String> entListKeys = new LinkedList<String>();
  55.   try {
  56.     Connection con = DataSource.getConnection();
  57.     Statement stmt = con.createStatement();
  58.    String query = "SELECT ENT_ASSIGN_KEY,ENT_LIST_KEY,OIU_KEY FROM ENT_ASSIGN ORDER BY 1 DESC ";
  59.     ResultSet rs = stmt.executeQuery(query);
  60.     while(rs.next()){
  61.      entListKeys.add(rs.getLong("ENT_LIST_KEY")+"");
  62.      accountKeys.add(rs.getLong("OIU_KEY")+"");
  63.     }
  64.   } catch (SQLException e) {   
  65.    e.printStackTrace();
  66.   }
  67.    entAssignData.put(accountKeys,entListKeys);
  68.   return entAssignData;
  69.   }
  70.   public Task getTaskDetailsByID(String taskId) throws IAMWorkflowException{
  71.       try {       
  72.         ITaskQueryService querySvc = wfSvcClient.getTaskQueryService();
  73.            wfCtx = getAdminWorkflowContext(querySvc);
  74.            Task task=querySvc.getTaskDetailsById(wfCtx,taskId);
  75.           return task;           
  76.       } catch(WorkflowException e) {
  77.           throw new IAMWorkflowException(e);
  78.       }
  79.   } 
  80.  private static HashMap<String,String> getPayloadValues(Element pElement) {
  81.       HashMap<String,String> map = new HashMap<String,String>();
  82.       NodeList nl = pElement.getChildNodes();
  83.       if(nl != null && nl.getLength() > 0) {
  84.         for (int i = 0; i < nl.getLength(); i++) {
  85.            String nodeName = nl.item(i).getNodeName();
  86.             NodeList subList = nl.item(i).getChildNodes();
  87.             if(subList != null && subList.getLength() > 0) {
  88.                   String nodeValue = subList.item(0).getNodeValue();
  89.                  // logger("Element is " + nodeName +
  90.                    //                " with a value of " + nodeValue);
  91.                   map.put(nodeName,nodeValue);
  92.             }
  93.         }
  94.       }
  95.         return map;
  96.     }
  97.  public void cleanupPendingEntitlements(Map<Object,Object> entAssgnData){   
  98.    logger( " validatePendingEntitlements Method getting called with entAssgnKeys ->"+entAssgnData);
  99.     try {       
  100.      List<Task> listOfTasksFrmSOA  = getManualFulfilmentTasks(entAssgnData);
  101.      if(listOfTasksFrmSOA!=null && listOfTasksFrmSOA.size() > 0){
  102.         logger( " Size of listOfTasksFrmSOA -> "+listOfTasksFrmSOA.size());
  103.          for (Task task : listOfTasksFrmSOA) {
  104.              String taskId = task.getSystemAttributes().getTaskId();
  105.              String title =  task.getTitle();
  106.             logger(" task-id = " + taskId  + "   \n task-title = "+ title);               
  107.              Task currentTask =   getTaskDetailsByID(taskId);
  108.              Element payload = currentTask.getPayloadAsElement();
  109.              HashMap<String,String> payloadValuesMap = getPayloadValues(payload);               
  110.              String entityType = (payloadValuesMap.get("EntityType") != null) ? (String) payloadValuesMap.get("EntityType") :"";
  111.              String provOperation=(payloadValuesMap.get("ProvisioningOperation") != null) ? (String) payloadValuesMap.get("ProvisioningOperation") :"";
  112.              if("Entitlement".equalsIgnoreCase(entityType)){
  113.               /*boolean recordInOIM = compareTaskWithEntAssignData(payloadValuesMap,entAssgnKeys);
  114.              logger("Does value exist for this task in OIM ?? = "+ recordInOIM);
  115.               if(recordInOIM) {*/
  116.                     logger(" OIM Entitlement Data exist for the task : " + taskId);
  117.                      boolean isAssignedToGroup = false;
  118.                      String assignee = getAssignee(task);
  119.                      if(task.getSystemAttributes().getAssigneeGroups() != null && task.getSystemAttributes().getAssigneeGroups().size()>0) {
  120.                          isAssignedToGroup = true;
  121.                      }
  122.                      rejectTask(task, taskId, assignee, isAssignedToGroup);
  123.                      logger("Done rejecting the task :"+ taskId);   
  124.              // }
  125.              }else {
  126.               logger("Resulted SOA task is not of type Entitlement...!");
  127.               }
  128.          }                                
  129.      }else{
  130.         logger( " listOfTasksFrmSOA Is NULL, There were no Matching records found in SOA...!"); 
  131.      }                                   
  132.          
  133.      }catch (Exception e){
  134.         logger("validatePendingEntitlements :  RejectTask method returns exception " +e);          
  135.      }
  136.  }
  137.     public void rejectTask(Task task, String taskId, String assginee, boolean isAssignedToGroup) throws Exception {     
  138.         ITaskService taskSvc =  wfSvcClient.getTaskService();
  139.         ITaskQueryService querySvc =  wfSvcClient.getTaskQueryService();
  140.         IWorkflowContext adminWorkflowCtx= getAdminWorkflowContext(querySvc);
  141.         wfCtx = querySvc.authenticateOnBehalfOf(adminWorkflowCtx, assginee);
  142.         System.out.println("  task.getSystemAttributes().getTaskId()   ->   " +task.getSystemAttributes().getTaskId());
  143.         System.out.println("  String taskId   ->   " +taskId);
  144.         if(isAssignedToGroup) {
  145.             taskSvc.acquireTask(wfCtx, task);
  146.         }
  147.         taskSvc.updateTaskOutcome(wfCtx, taskSvc.addComment(wfCtx, task.getSystemAttributes().getTaskId(), "Cleaning manual provisioniong task"),"REJECT");         
  148.     }     
  149.     private IWorkflowContext getAdminWorkflowContext(ITaskQueryService querySvc) throws WorkflowException {       
  150.         IWorkflowContext adminCtx;
  151.         String username = (String) bpelprops.get(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_PRINCIPAL);
  152.         String password = (String) bpelprops.get(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_SECURITY_CREDENTIALS);
  153.         adminCtx = querySvc.authenticate(username, password.toCharArray(), "jazn.com");
  154.         return adminCtx;
  155.     }
  156.     private String getAssignee(Task task) throws Exception {
  157.         String assignee = "";        
  158.         List<IdentityTypeImpl> assignedUsers = (List<IdentityTypeImpl>)task.getSystemAttributes().getAssignees();
  159.         
  160.         if (assignedUsers != null && assignedUsers.size() > 0) {
  161.             assignee = assignedUsers.get(0).getId();
  162.             return assignee;
  163.         }        
  164.         List<IdentityType> assignedGroups = task.getSystemAttributes().getAssigneeGroups();
  165.         if (assignedGroups != null && assignedGroups.size() > 0) {
  166.             String assingeeGroup = assignedGroups.get(0).getId();
  167.             if(assingeeGroup != null && assingeeGroup.isEmpty() == false) {
  168.              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' " +
  169.                                         "AND UGP.UGP_NAME  = ? ";
  170.              try{                
  171.                 tcDataSet moQds = new tcDataSet();              
  172.                 PreparedStatementUtil pstmt = new PreparedStatementUtil();
  173.                 pstmt.setStatement(XLDatabase.getInstance(), queryToGetAsignee);       
  174.                 pstmt.setString(1, assingeeGroup);              
  175.                 pstmt.execute();
  176.                 moQds = pstmt.getDataSet();   
  177.                     if(moQds.getRowCount()>0){
  178.                         moQds.goToRow(0); 
  179.                         assignee = moQds.getString("USR_LOGIN");
  180.                     }
  181.                 }catch(Exception sqlExp){
  182.                    logger( "getAssignee : Exception During Executing Query -> "+queryToGetAsignee + " with assingeeGroup -> "+assingeeGroup + " sqlExp -> "+sqlExp);
  183.                 }
  184.              }
  185.         }
  186.         return assignee;
  187.     }   
  188.     public List<Task> getManualFulfilmentTasks(Map<Object,Object> entAssgnData) throws IAMWorkflowException{       
  189.         ITaskQueryService querySvc =  wfSvcClient.getTaskQueryService();
  190.         try{
  191.             wfCtx = getAdminWorkflowContext(querySvc);
  192.             System.out.println( "Creating Predicate Object to filter only DisconnectedProvisioning tasks from SOA.");              
  193.             Predicate compositenamePredicate = new Predicate(TableConstants.WFTASKMETADATA_NAMESPACE_COLUMN,Predicate.OP_CONTAINS, "DisconnectedProvisioning");
  194.             // _.LOGGER.log(Level.FINER, "Adding Predicate Object to filter TASK_STATE_ASSIGNED OR TASK_STATE_INFO_REQUESTED from SOA.");
  195.             Predicate predicate = new Predicate(Column.getColumn(WFTaskConstants.STATE_COLUMN), Predicate.OP_EQ, IWorkflowConstants.TASK_STATE_ASSIGNED);
  196.             predicate.addClause(Predicate.OR, Column.getColumn(WFTaskConstants.STATE_COLUMN), Predicate.OP_EQ,IWorkflowConstants.TASK_STATE_INFO_REQUESTED);
  197.             // _.LOGGER.log(Level.FINER,"Adding filter Object to TEXTATTRIBUTE COLUMNs from SOA.");
  198.             Predicate textAttributePredicate =null;
  199.                 //For Loop Size will be always 1 which contains list objects accountKeys=OIU_KEY and entListKeys=ENT_LIST_KEY
  200.                 for (Map.Entry<Object, Object> entry : entAssgnData.entrySet()){ 
  201.                         List accountKeys = (LinkedList)entry.getKey();
  202.                         List entListKeys = (LinkedList)entry.getValue();                        
  203.                         textAttributePredicate = new Predicate(Column.getColumn(WFTaskConstants.TEXTATTRIBUTE7_COLUMN), Predicate.OP_IN, accountKeys);
  204.                         textAttributePredicate.addClause(Predicate.AND, Column.getColumn(WFTaskConstants.TEXTATTRIBUTE8_COLUMN), Predicate.OP_IN, entListKeys);
  205.                         predicate = new Predicate(predicate, Predicate.AND, textAttributePredicate);
  206.                     }            
  207.             compositenamePredicate = new Predicate(compositenamePredicate, Predicate.AND, predicate);            
  208.             System.out.println( "Preparing list query columns,which should exist in SOA result...!");
  209.             List<String> queryColumns = new ArrayList<String>();
  210.             queryColumns.add("TASKID");
  211.             queryColumns.add("TASKNUMBER");
  212.             queryColumns.add("TITLE");
  213.             queryColumns.add("OUTCOME");
  214.             queryColumns.add("STATE");
  215.             queryColumns.add("ASSIGNEDDATE");
  216.             queryColumns.add("ROOTTASKID");
  217.             queryColumns.add("ASSIGNEES");
  218.             queryColumns.add("ASSIGNEEGROUPS");    
  219.             List optionalInfo = new ArrayList();      
  220.             optionalInfo.add("Comments");             
  221.             List<Task> listOfTasksFrmSOA= null;
  222.             listOfTasksFrmSOA = querySvc.queryTasks(wfCtx, queryColumns, optionalInfo,ITaskQueryService.AssignmentFilter.ALL, null, compositenamePredicate,null, 0, 0);
  223.           System.out.println( " Returning  List object listOfTasksFrmSOA with Task details.");
  224.             return listOfTasksFrmSOA;            
  225.         } catch(WorkflowException e) {
  226.             throw new IAMWorkflowException(e);
  227.         }finally {
  228.                System.out.println( "Restoring run as subject");              
  229.                 }
  230.     }
  231.     public static void logger(String logStatement){
  232.      System.out.println("RejectPendingSOATasks  : -> " +logStatement);
  233.     }
  234. }


No comments:

Post a Comment