Coverage Report - org.kuali.rice.kew.engine.BlanketApproveEngine
 
Classes in this File Line Coverage Branch Coverage Complexity
BlanketApproveEngine
0%
0/120
0%
0/82
4.067
BlanketApproveEngine$ProcessEntry
0%
0/10
N/A
4.067
 
 1  
 /*
 2  
  * Copyright 2005-2007 The Kuali Foundation
 3  
  *
 4  
  *
 5  
  * Licensed under the Educational Community License, Version 2.0 (the "License");
 6  
  * you may not use this file except in compliance with the License.
 7  
  * You may obtain a copy of the License at
 8  
  *
 9  
  * http://www.opensource.org/licenses/ecl2.php
 10  
  *
 11  
  * Unless required by applicable law or agreed to in writing, software
 12  
  * distributed under the License is distributed on an "AS IS" BASIS,
 13  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14  
  * See the License for the specific language governing permissions and
 15  
  * limitations under the License.
 16  
  */
 17  
 package org.kuali.rice.kew.engine;
 18  
 
 19  
 import java.util.ArrayList;
 20  
 import java.util.HashSet;
 21  
 import java.util.Iterator;
 22  
 import java.util.LinkedList;
 23  
 import java.util.List;
 24  
 import java.util.Set;
 25  
 
 26  
 import org.apache.log4j.MDC;
 27  
 import org.kuali.rice.kew.actionrequest.ActionRequestFactory;
 28  
 import org.kuali.rice.kew.actionrequest.ActionRequestValue;
 29  
 import org.kuali.rice.kew.actionrequest.KimPrincipalRecipient;
 30  
 import org.kuali.rice.kew.actionrequest.service.ActionRequestService;
 31  
 import org.kuali.rice.kew.actions.NotificationContext;
 32  
 import org.kuali.rice.kew.actiontaken.ActionTakenValue;
 33  
 import org.kuali.rice.kew.api.WorkflowRuntimeException;
 34  
 import org.kuali.rice.kew.engine.node.Process;
 35  
 import org.kuali.rice.kew.engine.node.RouteNode;
 36  
 import org.kuali.rice.kew.engine.node.RouteNodeInstance;
 37  
 import org.kuali.rice.kew.exception.InvalidActionTakenException;
 38  
 import org.kuali.rice.kew.exception.WorkflowException;
 39  
 import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
 40  
 import org.kuali.rice.kew.service.KEWServiceLocator;
 41  
 import org.kuali.rice.kew.util.KEWConstants;
 42  
 
 43  
 
 44  
 /**
 45  
  * A WorkflowEngine implementation which orchestrates the document through the blanket approval process.
 46  
  *
 47  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 48  
  */
 49  
 public class BlanketApproveEngine extends StandardWorkflowEngine {
 50  
         
 51  0
         private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BlanketApproveEngine.class);
 52  
 
 53  
     private final OrchestrationConfig config;
 54  
 
 55  
     BlanketApproveEngine(OrchestrationConfig config) {
 56  0
         super(config.isRunPostProcessorLogic());
 57  0
         this.config = config;
 58  0
     }
 59  
 
 60  
     /**
 61  
      * Orchestrates the document through the blanket approval process. The termination of the process is keyed off of the Set of node names. If there are no node names, then the document will be blanket approved past the terminal node(s) in the document.
 62  
      */
 63  
     public void process(String documentId, String nodeInstanceId) throws Exception {
 64  0
         if (documentId == null) {
 65  0
             throw new IllegalArgumentException("Cannot process a null document id.");
 66  
         }
 67  0
         MDC.put("docId", documentId);
 68  0
         RouteContext context = RouteContext.getCurrentRouteContext();
 69  
         try {
 70  0
             KEWServiceLocator.getRouteHeaderService().lockRouteHeader(documentId, true);
 71  0
             if ( LOG.isInfoEnabled() ) {
 72  0
                     LOG.info("Processing document for Blanket Approval: " + documentId + " : " + nodeInstanceId);
 73  
             }
 74  0
             DocumentRouteHeaderValue document = getRouteHeaderService().getRouteHeader(documentId);
 75  0
             if (!document.isRoutable()) {
 76  0
                 LOG.debug("Document not routable so returning with doing no action");
 77  
                 return;
 78  
             }
 79  0
             List<RouteNodeInstance> activeNodeInstances = new ArrayList<RouteNodeInstance>();
 80  0
             if (nodeInstanceId == null) {
 81  0
                 activeNodeInstances.addAll(getRouteNodeService().getActiveNodeInstances(documentId));
 82  
             } else {
 83  0
                 RouteNodeInstance instanceNode = getRouteNodeService().findRouteNodeInstanceById(nodeInstanceId);
 84  0
                 if (instanceNode == null) {
 85  0
                     throw new IllegalArgumentException("Invalid node instance id: " + nodeInstanceId);
 86  
                 }
 87  0
                 activeNodeInstances.add(instanceNode);
 88  
             }
 89  0
             List<RouteNodeInstance> nodeInstancesToProcess = determineNodeInstancesToProcess(activeNodeInstances, config.getDestinationNodeNames());
 90  
 
 91  
 
 92  0
             context.setDoNotSendApproveNotificationEmails(true);
 93  0
             context.setDocument(document);
 94  0
             context.setEngineState(new EngineState());
 95  0
             NotificationContext notifyContext = null;
 96  0
             if (config.isSendNotifications()) {
 97  0
                 notifyContext = new NotificationContext(KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, config.getCause().getPrincipal(), config.getCause().getActionTaken());
 98  
             }
 99  0
             lockAdditionalDocuments(document);
 100  
             try {
 101  0
                 List<ProcessEntry> processingQueue = new LinkedList<ProcessEntry>();
 102  0
                 for (RouteNodeInstance nodeInstancesToProcesses : nodeInstancesToProcess)
 103  
                 {
 104  0
                     processingQueue.add(new ProcessEntry((RouteNodeInstance) nodeInstancesToProcesses));
 105  
                 }
 106  0
                 Set<String> nodesCompleted = new HashSet<String>();
 107  
                 // check the processingQueue for cases where there are no dest. nodes otherwise check if we've reached
 108  
                 // the dest. nodes
 109  0
                 while (!processingQueue.isEmpty() && !isReachedDestinationNodes(config.getDestinationNodeNames(), nodesCompleted)) {
 110  0
                     ProcessEntry entry = processingQueue.remove(0);
 111  
                     // TODO document magical join node workage (ask Eric)
 112  
                     // TODO this has been set arbitrarily high because the implemented processing model here will probably not work for
 113  
                     // large parallel object graphs. This needs to be re-evaluated, see KULWF-459.
 114  0
                     if (entry.getTimesProcessed() > 20) {
 115  0
                         throw new WorkflowException("Could not process document through to blanket approval." + "  Document failed to progress past node " + entry.getNodeInstance().getRouteNode().getRouteNodeName());
 116  
                     }
 117  0
                     RouteNodeInstance nodeInstance = entry.getNodeInstance();
 118  0
                     context.setNodeInstance(nodeInstance);
 119  0
                     if (config.getDestinationNodeNames().contains(nodeInstance.getName())) {
 120  0
                         nodesCompleted.add(nodeInstance.getName());
 121  0
                         continue;
 122  
                     }
 123  0
                     ProcessContext resultProcessContext = processNodeInstance(context, helper);
 124  0
                     invokeBlanketApproval(config.getCause(), nodeInstance, notifyContext);
 125  0
                     if (!resultProcessContext.getNextNodeInstances().isEmpty() || resultProcessContext.isComplete()) {
 126  0
                         for (Iterator nodeIt = resultProcessContext.getNextNodeInstances().iterator(); nodeIt.hasNext();) {
 127  0
                             addToProcessingQueue(processingQueue, (RouteNodeInstance) nodeIt.next());
 128  
                         }
 129  
                     } else {
 130  0
                         entry.increment();
 131  0
                         processingQueue.add(processingQueue.size(), entry);
 132  
                     }
 133  0
                 }
 134  
                 //clear the context so the standard engine can begin routing normally
 135  0
                 RouteContext.clearCurrentRouteContext();
 136  
                 // continue with normal routing after blanket approve brings us to the correct place
 137  
                 // if there is an active approve request this is no-op.
 138  0
                 super.process(documentId, null);
 139  0
             } catch (Exception e) {
 140  0
                     if (e instanceof RuntimeException) {
 141  0
                         throw (RuntimeException)e;
 142  
                 } else {
 143  0
                         throw new WorkflowRuntimeException(e.toString(), e);
 144  
                 }
 145  0
             }
 146  
         } finally {
 147  0
                 RouteContext.clearCurrentRouteContext();
 148  0
             MDC.remove("docId");
 149  0
         }
 150  0
     }
 151  
 
 152  
     /**
 153  
      * @return true if all destination node are active but not yet complete - ready for the standard engine to take over the activation process for requests
 154  
      */
 155  
     private boolean isReachedDestinationNodes(Set destinationNodesNames, Set<String> nodeNamesCompleted) {
 156  0
         return !destinationNodesNames.isEmpty() && nodeNamesCompleted.equals(destinationNodesNames);
 157  
     }
 158  
 
 159  
     private void addToProcessingQueue(List<ProcessEntry> processingQueue, RouteNodeInstance nodeInstance) {
 160  
         // first, detect if it's already there
 161  0
         for (ProcessEntry entry : processingQueue)
 162  
         {
 163  0
             if (entry.getNodeInstance().getRouteNodeInstanceId().equals(nodeInstance.getRouteNodeInstanceId()))
 164  
             {
 165  0
                 entry.setNodeInstance(nodeInstance);
 166  0
                 return;
 167  
             }
 168  
         }
 169  0
         processingQueue.add(processingQueue.size(), new ProcessEntry(nodeInstance));
 170  0
     }
 171  
 
 172  
     /**
 173  
      * If there are multiple paths, we need to figure out which ones we need to follow for blanket approval. This method will throw an exception if a node with the given name could not be located in the routing path. This method is written in such a way that it should be impossible for there to be an infinite loop, even if there is extensive looping in the node graph.
 174  
      */
 175  
     private List<RouteNodeInstance> determineNodeInstancesToProcess(List<RouteNodeInstance> activeNodeInstances, Set nodeNames) throws Exception {
 176  0
         if (nodeNames.isEmpty()) {
 177  0
             return activeNodeInstances;
 178  
         }
 179  0
         List<RouteNodeInstance> nodeInstancesToProcess = new ArrayList<RouteNodeInstance>();
 180  0
         for (Iterator<RouteNodeInstance> iterator = activeNodeInstances.iterator(); iterator.hasNext();) {
 181  0
             RouteNodeInstance nodeInstance = (RouteNodeInstance) iterator.next();
 182  0
             if (isNodeNameInPath(nodeNames, nodeInstance)) {
 183  0
                 nodeInstancesToProcess.add(nodeInstance);
 184  
             }
 185  0
         }
 186  0
         if (nodeInstancesToProcess.size() == 0) {
 187  0
             throw new InvalidActionTakenException("Could not locate nodes with the given names in the blanket approval path '" + printNodeNames(nodeNames) + "'.  " + "The document is probably already passed the specified nodes or does not contain the nodes.");
 188  
         }
 189  0
         return nodeInstancesToProcess;
 190  
     }
 191  
 
 192  
     private boolean isNodeNameInPath(Set nodeNames, RouteNodeInstance nodeInstance) throws Exception {
 193  0
         boolean isInPath = false;
 194  0
         for (Object nodeName1 : nodeNames)
 195  
         {
 196  0
             String nodeName = (String) nodeName1;
 197  0
             for (RouteNode nextNode : nodeInstance.getRouteNode().getNextNodes())
 198  
             {
 199  0
                 isInPath = isInPath || isNodeNameInPath(nodeName, nextNode, new HashSet<String>());
 200  
             }
 201  0
         }
 202  0
         return isInPath;
 203  
     }
 204  
 
 205  
     private boolean isNodeNameInPath(String nodeName, RouteNode node, Set<String> inspected) throws Exception {
 206  0
         boolean isInPath = !inspected.contains(node.getRouteNodeId()) && node.getRouteNodeName().equals(nodeName);
 207  0
         inspected.add(node.getRouteNodeId());
 208  0
         if (helper.isSubProcessNode(node)) {
 209  0
             Process subProcess = node.getDocumentType().getNamedProcess(node.getRouteNodeName());
 210  0
             RouteNode subNode = subProcess.getInitialRouteNode();
 211  0
             isInPath = isInPath || isNodeNameInPath(nodeName, subNode, inspected);
 212  
         }
 213  0
         for (RouteNode nextNode : node.getNextNodes())
 214  
         {
 215  0
             isInPath = isInPath || isNodeNameInPath(nodeName, nextNode, inspected);
 216  
         }
 217  0
         return isInPath;
 218  
     }
 219  
 
 220  
     private String printNodeNames(Set nodesNames) {
 221  0
         StringBuffer buffer = new StringBuffer();
 222  0
         for (Iterator iterator = nodesNames.iterator(); iterator.hasNext();) {
 223  0
             String nodeName = (String) iterator.next();
 224  0
             buffer.append(nodeName);
 225  0
             buffer.append((iterator.hasNext() ? ", " : ""));
 226  0
         }
 227  0
         return buffer.toString();
 228  
     }
 229  
 
 230  
     /**
 231  
      * Invokes the blanket approval for the given node instance. This deactivates all pending approve or complete requests at the node and sends out notifications to the individuals who's requests were trumped by the blanket approve.
 232  
      */
 233  
     private void invokeBlanketApproval(ActionTakenValue actionTaken, RouteNodeInstance nodeInstance, NotificationContext notifyContext) {
 234  0
         List actionRequests = getActionRequestService().findPendingRootRequestsByDocIdAtRouteNode(nodeInstance.getDocumentId(), nodeInstance.getRouteNodeInstanceId());
 235  0
         actionRequests = getActionRequestService().getRootRequests(actionRequests);
 236  0
         List<ActionRequestValue> requestsToNotify = new ArrayList<ActionRequestValue>();
 237  0
         for (Iterator iterator = actionRequests.iterator(); iterator.hasNext();) {
 238  0
             ActionRequestValue request = (ActionRequestValue) iterator.next();
 239  0
             if (request.isApproveOrCompleteRequest()) {
 240  0
                 getActionRequestService().deactivateRequest(actionTaken, request);
 241  0
                 requestsToNotify.add(request);
 242  
             }
 243  0
         }
 244  0
         if (notifyContext != null) {
 245  0
                 ActionRequestFactory arFactory = new ActionRequestFactory(RouteContext.getCurrentRouteContext().getDocument(), nodeInstance);
 246  0
                 KimPrincipalRecipient delegatorRecipient = null;
 247  0
                 if (actionTaken.getDelegatorPrincipal() != null) {
 248  0
                         delegatorRecipient = new KimPrincipalRecipient(actionTaken.getDelegatorPrincipal());
 249  
                 }
 250  0
                 List<ActionRequestValue> notificationRequests = arFactory.generateNotifications(requestsToNotify, notifyContext.getPrincipalTakingAction(), delegatorRecipient, notifyContext.getNotificationRequestCode(), notifyContext.getActionTakenCode());
 251  0
                 getActionRequestService().activateRequests(notificationRequests);
 252  
         }
 253  0
     }
 254  
 
 255  
     private ActionRequestService getActionRequestService() {
 256  0
         return KEWServiceLocator.getActionRequestService();
 257  
     }
 258  
 
 259  
     private class ProcessEntry {
 260  
 
 261  
         private RouteNodeInstance nodeInstance;
 262  0
         private int timesProcessed = 0;
 263  
 
 264  0
         public ProcessEntry(RouteNodeInstance nodeInstance) {
 265  0
             this.nodeInstance = nodeInstance;
 266  0
         }
 267  
 
 268  
         public RouteNodeInstance getNodeInstance() {
 269  0
             return nodeInstance;
 270  
         }
 271  
 
 272  
         public void setNodeInstance(RouteNodeInstance nodeInstance) {
 273  0
             this.nodeInstance = nodeInstance;
 274  0
         }
 275  
 
 276  
         public void increment() {
 277  0
             timesProcessed++;
 278  0
         }
 279  
 
 280  
         public int getTimesProcessed() {
 281  0
             return timesProcessed;
 282  
         }
 283  
 
 284  
     }
 285  
 
 286  
 }