Coverage Report - org.kuali.rice.kew.engine.StandardWorkflowEngine
 
Classes in this File Line Coverage Branch Coverage Complexity
StandardWorkflowEngine
0%
0/342
0%
0/176
4.839
 
 1  
 /*
 2  
  * Copyright 2006-2011 The Kuali Foundation
 3  
  *
 4  
  * Licensed under the Educational Community License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  * http://www.opensource.org/licenses/ecl2.php
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  */
 16  
 
 17  
 package org.kuali.rice.kew.engine;
 18  
 
 19  
 import org.apache.log4j.MDC;
 20  
 import org.kuali.rice.core.framework.parameter.ParameterService;
 21  
 import org.kuali.rice.kew.actionrequest.ActionRequestValue;
 22  
 import org.kuali.rice.kew.engine.node.Branch;
 23  
 import org.kuali.rice.kew.engine.node.BranchState;
 24  
 import org.kuali.rice.kew.engine.node.Process;
 25  
 import org.kuali.rice.kew.engine.node.ProcessResult;
 26  
 import org.kuali.rice.kew.engine.node.RouteNodeInstance;
 27  
 import org.kuali.rice.kew.engine.node.RouteNodeUtils;
 28  
 import org.kuali.rice.kew.engine.node.service.RouteNodeService;
 29  
 import org.kuali.rice.kew.engine.transition.Transition;
 30  
 import org.kuali.rice.kew.engine.transition.TransitionEngine;
 31  
 import org.kuali.rice.kew.engine.transition.TransitionEngineFactory;
 32  
 import org.kuali.rice.kew.exception.InvalidActionTakenException;
 33  
 import org.kuali.rice.kew.exception.RouteManagerException;
 34  
 import org.kuali.rice.kew.exception.WorkflowException;
 35  
 import org.kuali.rice.kew.postprocessor.AfterProcessEvent;
 36  
 import org.kuali.rice.kew.postprocessor.BeforeProcessEvent;
 37  
 import org.kuali.rice.kew.postprocessor.DefaultPostProcessor;
 38  
 import org.kuali.rice.kew.postprocessor.DocumentLockingEvent;
 39  
 import org.kuali.rice.kew.postprocessor.DocumentRouteLevelChange;
 40  
 import org.kuali.rice.kew.postprocessor.DocumentRouteStatusChange;
 41  
 import org.kuali.rice.kew.postprocessor.PostProcessor;
 42  
 import org.kuali.rice.kew.postprocessor.ProcessDocReport;
 43  
 import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
 44  
 import org.kuali.rice.kew.routeheader.service.RouteHeaderService;
 45  
 import org.kuali.rice.kew.service.KEWServiceLocator;
 46  
 import org.kuali.rice.kew.util.KEWConstants;
 47  
 import org.kuali.rice.kew.util.PerformanceLogger;
 48  
 import org.kuali.rice.kns.util.KNSConstants;
 49  
 
 50  
 import java.util.ArrayList;
 51  
 import java.util.Collection;
 52  
 import java.util.Iterator;
 53  
 import java.util.LinkedList;
 54  
 import java.util.List;
 55  
 
 56  
 
 57  
 /**
 58  
  * The standard and supported implementation of the WorkflowEngine.  Runs a processing loop against a given
 59  
  * Document, processing nodes on the document until the document is completed or a node halts the
 60  
  * processing.
 61  
  *
 62  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 63  
  */
 64  
 public class StandardWorkflowEngine implements WorkflowEngine {
 65  
 
 66  0
         private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(StandardWorkflowEngine.class);
 67  
 
 68  0
         protected RouteHelper helper = new RouteHelper();
 69  0
         private boolean runPostProcessorLogic = true;
 70  
     private RouteNodeService routeNodeService;
 71  
     private RouteHeaderService routeHeaderService;
 72  
     private ParameterService parameterService;
 73  
 
 74  0
     public StandardWorkflowEngine() {}
 75  
 
 76  0
         public StandardWorkflowEngine(boolean runPostProcessorLogic) {
 77  0
             setRunPostProcessorLogic(runPostProcessorLogic);
 78  0
         }
 79  
 
 80  
         public void setRunPostProcessorLogic(boolean runPostProcessorLogic) {
 81  0
             this.runPostProcessorLogic = runPostProcessorLogic;
 82  0
         }
 83  
 
 84  
         public boolean isRunPostProcessorLogic() {
 85  0
             return this.runPostProcessorLogic;
 86  
         }
 87  
 
 88  
         public void process(String documentId, Long nodeInstanceId) throws Exception {
 89  0
                 if (documentId == null) {
 90  0
                         throw new IllegalArgumentException("Cannot process a null document id.");
 91  
                 }
 92  0
                 MDC.put("docId", documentId);
 93  0
                 boolean success = true;
 94  0
                 RouteContext context = RouteContext.createNewRouteContext();
 95  
                 try {
 96  0
                         if ( LOG.isInfoEnabled() ) {
 97  0
                                 LOG.info("Aquiring lock on document " + documentId);
 98  
                         }
 99  0
                         KEWServiceLocator.getRouteHeaderService().lockRouteHeader(documentId, true);
 100  0
                         if ( LOG.isInfoEnabled() ) {
 101  0
                                 LOG.info("Aquired lock on document " + documentId);
 102  
                         }
 103  
 
 104  0
                         DocumentRouteHeaderValue document = getRouteHeaderService().getRouteHeader(documentId);
 105  0
                         context.setDocument(document);
 106  0
                         lockAdditionalDocuments(document);
 107  
 
 108  0
                         if ( LOG.isInfoEnabled() ) {
 109  0
                                 LOG.info("Processing document: " + documentId + " : " + nodeInstanceId);
 110  
                         }
 111  
 
 112  
                         try {
 113  0
                     document = notifyPostProcessorBeforeProcess(document, nodeInstanceId);
 114  0
                     context.setDocument(document);
 115  0
             } catch (Exception e) {
 116  0
                 LOG.warn("Problems contacting PostProcessor before engine process", e);
 117  0
                 throw new RouteManagerException("Problems contacting PostProcessor:  " + e.getMessage());
 118  0
             }
 119  0
             if (!document.isRoutable()) {
 120  0
                                 LOG.debug("Document not routable so returning with doing no action");
 121  
                                 return;
 122  
                         }
 123  0
                         List nodeInstancesToProcess = new LinkedList();
 124  0
                         if (nodeInstanceId == null) {
 125  
                                 // pulls the node instances from the passed in document
 126  0
                                 nodeInstancesToProcess.addAll(RouteNodeUtils.getActiveNodeInstances(document));
 127  
                         } else {
 128  0
                                 RouteNodeInstance instanceNode = RouteNodeUtils.findRouteNodeInstanceById(nodeInstanceId,document);
 129  0
                                 if (instanceNode == null) {
 130  0
                                         throw new IllegalArgumentException("Invalid node instance id: " + nodeInstanceId);
 131  
                                 }
 132  0
                                 nodeInstancesToProcess.add(instanceNode);
 133  
                         }
 134  
 
 135  0
                         context.setEngineState(new EngineState());
 136  0
                         ProcessContext processContext = new ProcessContext(true, nodeInstancesToProcess);
 137  
                         try {
 138  0
                                 while (!nodeInstancesToProcess.isEmpty()) {
 139  0
                                         context.setNodeInstance((RouteNodeInstance) nodeInstancesToProcess.remove(0));
 140  0
                                         processContext = processNodeInstance(context, helper);
 141  0
                                         if (processContext.isComplete() && !processContext.getNextNodeInstances().isEmpty()) {
 142  0
                                                 nodeInstancesToProcess.addAll(processContext.getNextNodeInstances());
 143  
                                         }
 144  
                                 }
 145  0
                                 context.setDocument(nodePostProcess(context));
 146  0
                         } catch (Exception e) {
 147  0
                                 success = false;
 148  
                                 // TODO throw a new 'RoutingException' which holds the
 149  
                                 // RoutingState
 150  0
                                 throw new RouteManagerException(e, context);
 151  0
                         }
 152  
                 } finally {
 153  0
                         if ( LOG.isInfoEnabled() ) {
 154  0
                                 LOG.info((success ? "Successfully processed" : "Failed to process") + " document: " + documentId + " : " + nodeInstanceId);
 155  
                         }
 156  
                         try {
 157  0
                     notifyPostProcessorAfterProcess(context.getDocument(), nodeInstanceId, success);
 158  0
             } catch (Exception e) {
 159  0
                 LOG.warn("Problems contacting PostProcessor after engine process", e);
 160  0
                 throw new RouteManagerException("Problems contacting PostProcessor:  " + e.getMessage(), context);
 161  0
             }
 162  0
                         RouteContext.clearCurrentRouteContext();
 163  0
                         MDC.remove("docId");
 164  0
                 }
 165  0
         }
 166  
 
 167  
         protected ProcessContext processNodeInstance(RouteContext context, RouteHelper helper) throws Exception {
 168  0
                 RouteNodeInstance nodeInstance = context.getNodeInstance();
 169  0
                 if ( LOG.isDebugEnabled() ) {
 170  0
                         LOG.debug("Processing node instance: " + nodeInstance.getRouteNode().getRouteNodeName());
 171  
                 }
 172  0
                 if (checkAssertions(context)) {
 173  
                         // returning an empty context causes the outer loop to terminate
 174  0
                         return new ProcessContext();
 175  
                 }
 176  0
                 TransitionEngine transitionEngine = TransitionEngineFactory.createTransitionEngine(nodeInstance);
 177  0
                 ProcessResult processResult = transitionEngine.isComplete(context);
 178  0
                 nodeInstance.setInitial(false);
 179  
 
 180  
                 // if this nodeInstance already has next node instance we don't need to
 181  
                 // go to the TE
 182  0
                 if (processResult.isComplete()) {
 183  0
                         if ( LOG.isDebugEnabled() ) {
 184  0
                                 LOG.debug("Routing node has completed: " + nodeInstance.getRouteNode().getRouteNodeName());
 185  
                         }
 186  
 
 187  0
                         context.getEngineState().getCompleteNodeInstances().add(nodeInstance.getRouteNodeInstanceId());
 188  0
                         List nextNodeCandidates = invokeTransition(context, context.getNodeInstance(), processResult, transitionEngine);
 189  
 
 190  
                         // iterate over the next node candidates sending them through the
 191  
                         // transition engine's transitionTo method
 192  
                         // one at a time for a potential switch. Place the transition
 193  
                         // engines result back in the 'actual' next node
 194  
                         // list which we put in the next node before doing work.
 195  0
                         List<RouteNodeInstance> nodesToActivate = new ArrayList<RouteNodeInstance>();
 196  0
                         if (!nextNodeCandidates.isEmpty()) {
 197  
                                 // KULRICE-4274: Hierarchy Routing Node issues
 198  
                                 // No longer change nextNodeInstances in place, instead we create a local and assign our local list below
 199  
                                 // the loop so the post processor doesn't save a RouteNodeInstance in an intermediate state
 200  0
                                 ArrayList<RouteNodeInstance> nextNodeInstances = new ArrayList<RouteNodeInstance>();
 201  
 
 202  0
                                 for (Iterator nextIt = nextNodeCandidates.iterator(); nextIt.hasNext();) {
 203  0
                                         RouteNodeInstance nextNodeInstance = (RouteNodeInstance) nextIt.next();
 204  0
                                         transitionEngine = TransitionEngineFactory.createTransitionEngine(nextNodeInstance);
 205  0
                                         RouteNodeInstance currentNextNodeInstance = nextNodeInstance;
 206  0
                                         nextNodeInstance = transitionEngine.transitionTo(nextNodeInstance, context);
 207  
                                         // if the next node has changed, we need to remove our
 208  
                                         // current node as a next node of the original node
 209  0
                                         if (!currentNextNodeInstance.equals(nextNodeInstance)) {
 210  0
                                                 currentNextNodeInstance.getPreviousNodeInstances().remove(nodeInstance);
 211  
                                         }
 212  
                                         // before adding next node instance, be sure that it's not
 213  
                                         // already linked via previous node instances
 214  
                                         // this is to prevent the engine from setting up references
 215  
                                         // on nodes that already reference each other.
 216  
                                         // the primary case being when we are walking over an
 217  
                                         // already constructed graph of nodes returned from a
 218  
                                         // dynamic node - probably a more sensible approach would be
 219  
                                         // to check for the existence of the link and moving on
 220  
                                         // if it's been established.
 221  0
                                         nextNodeInstance.getPreviousNodeInstances().remove(nodeInstance);
 222  0
                                         nextNodeInstances.add(nextNodeInstance);
 223  0
                                         handleBackwardCompatibility(context, nextNodeInstance);
 224  
                                         // call the post processor
 225  0
                                         notifyNodeChange(context, nextNodeInstance);
 226  0
                                         nodesToActivate.add(nextNodeInstance);
 227  
                                          // TODO update document content on context?
 228  0
                                  }
 229  
                                  // assign our local list here so the post processor doesn't save a RouteNodeInstance in an intermediate state
 230  0
                                 for (RouteNodeInstance nextNodeInstance : nextNodeInstances) {
 231  0
                                         nodeInstance.addNextNodeInstance(nextNodeInstance);
 232  
                                 }
 233  
                          }
 234  
  
 235  
                          // deactive the current active node
 236  0
                         nodeInstance.setComplete(true);
 237  0
                         nodeInstance.setActive(false);
 238  
                         // active the nodes we're transitioning into
 239  0
                         for (RouteNodeInstance nodeToActivate : nodesToActivate) {
 240  0
                                 nodeToActivate.setActive(true);
 241  
                         }
 242  0
                 } else {
 243  0
                     nodeInstance.setComplete(false);
 244  
         }
 245  
 
 246  0
                 saveNode(context, nodeInstance);
 247  0
                 return new ProcessContext(nodeInstance.isComplete(), nodeInstance.getNextNodeInstances());
 248  
         }
 249  
 
 250  
         /**
 251  
          * Checks various assertions regarding the processing of the current node.
 252  
          * If this method returns true, then the node will not be processed.
 253  
          *
 254  
          * This method will throw an exception if it deems that the processing is in
 255  
          * a illegal state.
 256  
          */
 257  
         private boolean checkAssertions(RouteContext context) throws Exception {
 258  0
                 if (context.getNodeInstance().isComplete()) {
 259  0
                         if ( LOG.isDebugEnabled() ) {
 260  0
                                 LOG.debug("The node has already been completed: " + context.getNodeInstance().getRouteNode().getRouteNodeName());
 261  
                         }
 262  0
                         return true;
 263  
                 }
 264  0
                 if (isRunawayProcessDetected(context.getEngineState())) {
 265  
 //                         TODO more info in message
 266  0
                         throw new WorkflowException("Detected runaway process.");
 267  
                 }
 268  0
                 return false;
 269  
         }
 270  
 
 271  
         /**
 272  
          * Invokes the transition and returns the next node instances to transition
 273  
          * to from the current node instance on the route context.
 274  
          *
 275  
          * This is a 3-step process:
 276  
          *
 277  
          * <pre>
 278  
          *  1) If the node instance already has next nodes, return those,
 279  
          *  2) otherwise, invoke the transition engine for the node, if the resulting node instances are not empty, return those,
 280  
          *  3) lastly, if our node is in a process and no next nodes were returned from it's transition engine, invoke the
 281  
          *     transition engine of the process node and return the resulting node instances.
 282  
          * </pre>
 283  
          */
 284  
         /*
 285  
          * private List invokeTransition(RouteContext context, RouteNodeInstance
 286  
          * nodeInstance, ProcessResult processResult, TransitionEngine
 287  
          * transitionEngine) throws Exception { List nextNodeInstances =
 288  
          * nodeInstance.getNextNodeInstances(); if (nextNodeInstances.isEmpty()) {
 289  
          * Transition result = transitionEngine.transitionFrom(context,
 290  
          * processResult); nextNodeInstances = result.getNextNodeInstances(); if
 291  
          * (nextNodeInstances.isEmpty() && nodeInstance.isInProcess()) {
 292  
          * transitionEngine =
 293  
          * TransitionEngineFactory.createTransitionEngine(nodeInstance.getProcess());
 294  
          * nextNodeInstances = invokeTransition(context, nodeInstance.getProcess(),
 295  
          * processResult, transitionEngine); } } return nextNodeInstances; }
 296  
          */
 297  
 
 298  
         private List invokeTransition(RouteContext context, RouteNodeInstance nodeInstance, ProcessResult processResult, TransitionEngine transitionEngine) throws Exception {
 299  0
                 List nextNodeInstances = nodeInstance.getNextNodeInstances();
 300  0
                 if (nextNodeInstances.isEmpty()) {
 301  0
                         Transition result = transitionEngine.transitionFrom(context, processResult);
 302  0
                         nextNodeInstances = result.getNextNodeInstances();
 303  0
                         if (nextNodeInstances.isEmpty() && nodeInstance.isInProcess()) {
 304  0
                                 transitionEngine = TransitionEngineFactory.createTransitionEngine(nodeInstance.getProcess());
 305  0
                                 context.setNodeInstance(nodeInstance);
 306  0
                                 nextNodeInstances = invokeTransition(context, nodeInstance.getProcess(), processResult, transitionEngine);
 307  
                         }
 308  
                 }
 309  0
                 return nextNodeInstances;
 310  
         }
 311  
 
 312  
         /*
 313  
          * private List invokeTransition(RouteContext context, RouteNodeInstance
 314  
          * process, ProcessResult processResult) throws Exception {
 315  
          * RouteNodeInstance nodeInstance = (context.getNodeInstance() ; List
 316  
          * nextNodeInstances = nodeInstance.getNextNodeInstances(); if
 317  
          * (nextNodeInstances.isEmpty()) { TransitionEngine transitionEngine =
 318  
          * TransitionEngineFactory.createTransitionEngine(nodeInstance); Transition
 319  
          * result = transitionEngine.transitionFrom(context, processResult);
 320  
          * nextNodeInstances = result.getNextNodeInstances(); if
 321  
          * (nextNodeInstances.isEmpty() && nodeInstance.isInProcess()) {
 322  
          * transitionEngine =
 323  
          * TransitionEngineFactory.createTransitionEngine(nodeInstance.getProcess());
 324  
          * nextNodeInstances = invokeTransition(context, nodeInstance.getProcess(),
 325  
          * processResult, transitionEngine); } } return nextNodeInstances; }
 326  
          *
 327  
          */private void notifyNodeChange(RouteContext context, RouteNodeInstance nextNodeInstance) throws Exception {
 328  0
                 if (!context.isSimulation()) {
 329  0
                         RouteNodeInstance nodeInstance = context.getNodeInstance();
 330  
                         // if application document status transition has been defined, update the status
 331  0
                         String nextStatus = nodeInstance.getRouteNode().getNextDocStatus();
 332  0
                         if (nextStatus != null && nextStatus.length() > 0){
 333  0
                                 context.getDocument().updateAppDocStatus(nextStatus);
 334  
                         }
 335  
 
 336  0
                         DocumentRouteLevelChange event = new DocumentRouteLevelChange(context.getDocument().getDocumentId(), context.getDocument().getAppDocId(), CompatUtils.getLevelForNode(context.getDocument().getDocumentType(), context.getNodeInstance()
 337  
                                         .getRouteNode().getRouteNodeName()), CompatUtils.getLevelForNode(context.getDocument().getDocumentType(), nextNodeInstance.getRouteNode().getRouteNodeName()), nodeInstance.getRouteNode().getRouteNodeName(), nextNodeInstance
 338  
                                         .getRouteNode().getRouteNodeName(), nodeInstance.getRouteNodeInstanceId(), nextNodeInstance.getRouteNodeInstanceId());
 339  0
                         context.setDocument(notifyPostProcessor(context.getDocument(), nodeInstance, event));
 340  
                 }
 341  0
         }
 342  
 
 343  
         private void handleBackwardCompatibility(RouteContext context, RouteNodeInstance nextNodeInstance) {
 344  0
                 context.getDocument().setDocRouteLevel(new Integer(context.getDocument().getDocRouteLevel().intValue() + 1)); // preserve
 345  
                                                                                                                                                                                                                                                 // route
 346  
                                                                                                                                                                                                                                                 // level
 347  
                                                                                                                                                                                                                                                 // concept
 348  
                                                                                                                                                                                                                                                 // if
 349  
                                                                                                                                                                                                                                                 // possible
 350  0
                 saveDocument(context);
 351  0
         }
 352  
 
 353  
         private void saveDocument(RouteContext context) {
 354  0
                 if (!context.isSimulation()) {
 355  0
                         getRouteHeaderService().saveRouteHeader(context.getDocument());
 356  
                 }
 357  0
         }
 358  
 
 359  
         private void saveBranch(RouteContext context, Branch branch) {
 360  0
                 if (!context.isSimulation()) {
 361  0
                         KEWServiceLocator.getRouteNodeService().save(branch);
 362  
                 }
 363  0
         }
 364  
 
 365  
         protected void saveNode(RouteContext context, RouteNodeInstance nodeInstance) {
 366  0
                 if (!context.isSimulation()) {
 367  0
                         getRouteNodeService().save(nodeInstance);
 368  
                 } else {
 369  
                         // if we are in simulation mode, lets go ahead and assign some id
 370  
                         // values to our beans
 371  0
                         for (Iterator<RouteNodeInstance> iterator = nodeInstance.getNextNodeInstances().iterator(); iterator.hasNext();) {
 372  0
                                 RouteNodeInstance routeNodeInstance = (RouteNodeInstance) iterator.next();
 373  0
                                 if (routeNodeInstance.getRouteNodeInstanceId() == null) {
 374  0
                                         routeNodeInstance.setRouteNodeInstanceId(context.getEngineState().getNextSimulationId());
 375  
                                 }
 376  0
                         }
 377  0
                         if (nodeInstance.getProcess() != null && nodeInstance.getProcess().getRouteNodeInstanceId() == null) {
 378  0
                                 nodeInstance.getProcess().setRouteNodeInstanceId(context.getEngineState().getNextSimulationId());
 379  
                         }
 380  0
                         if (nodeInstance.getBranch() != null && nodeInstance.getBranch().getBranchId() == null) {
 381  0
                                 nodeInstance.getBranch().setBranchId(context.getEngineState().getNextSimulationId());
 382  
                         }
 383  
                 }
 384  0
         }
 385  
 
 386  
         // TODO extract this into some sort of component which handles transitioning
 387  
         // document state
 388  
         protected DocumentRouteHeaderValue nodePostProcess(RouteContext context) throws InvalidActionTakenException {
 389  0
                 DocumentRouteHeaderValue document = context.getDocument();
 390  0
                 Collection<RouteNodeInstance> activeNodes = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());
 391  0
                 boolean moreNodes = false;
 392  0
                 for (Iterator<RouteNodeInstance> iterator = activeNodes.iterator(); iterator.hasNext();) {
 393  0
                         RouteNodeInstance nodeInstance = (RouteNodeInstance) iterator.next();
 394  0
                         moreNodes = moreNodes || !nodeInstance.isComplete();
 395  0
                 }
 396  0
                 List pendingRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
 397  0
                 boolean activeApproveRequests = false;
 398  0
                 boolean activeAckRequests = false;
 399  0
                 for (Iterator iterator = pendingRequests.iterator(); iterator.hasNext();) {
 400  0
                         ActionRequestValue request = (ActionRequestValue) iterator.next();
 401  0
                         activeApproveRequests = request.isApproveOrCompleteRequest() || activeApproveRequests;
 402  0
                         activeAckRequests = request.isAcknowledgeRequest() || activeAckRequests;
 403  0
                 }
 404  
                 // TODO is the logic for going processed still going to be valid?
 405  0
                 if (!document.isProcessed() && (!moreNodes || !activeApproveRequests)) {
 406  0
                         if ( LOG.isDebugEnabled() ) {
 407  0
                                 LOG.debug("No more nodes for this document " + document.getDocumentId());
 408  
                         }
 409  
                         // TODO perhaps the policies could also be factored out?
 410  0
                         checkDefaultApprovalPolicy(document);
 411  0
                         LOG.debug("Marking document approved");
 412  
                         // TODO factor out this magical post processing
 413  0
                         DocumentRouteStatusChange event = new DocumentRouteStatusChange(document.getDocumentId(), document.getAppDocId(), document.getDocRouteStatus(), KEWConstants.ROUTE_HEADER_APPROVED_CD);
 414  0
                         document.markDocumentApproved();
 415  
                         // saveDocument(context);
 416  0
                         notifyPostProcessor(context, event);
 417  
 
 418  0
                         LOG.debug("Marking document processed");
 419  0
                         event = new DocumentRouteStatusChange(document.getDocumentId(), document.getAppDocId(), document.getDocRouteStatus(), KEWConstants.ROUTE_HEADER_PROCESSED_CD);
 420  0
                         document.markDocumentProcessed();
 421  
                         // saveDocument(context);
 422  0
                         notifyPostProcessor(context, event);
 423  
                 }
 424  
 
 425  
                 // if document is processed and no pending action requests put the
 426  
                 // document into the finalized state.
 427  0
                 if (document.isProcessed()) {
 428  0
                         DocumentRouteStatusChange event = new DocumentRouteStatusChange(document.getDocumentId(), document.getAppDocId(), document.getDocRouteStatus(), KEWConstants.ROUTE_HEADER_FINAL_CD);
 429  0
                         List actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
 430  0
                         if (actionRequests.isEmpty()) {
 431  0
                                 document.markDocumentFinalized();
 432  
                                 // saveDocument(context);
 433  0
                                 notifyPostProcessor(context, event);
 434  
                         } else {
 435  0
                                 boolean markFinalized = true;
 436  0
                                 for (Iterator iter = actionRequests.iterator(); iter.hasNext();) {
 437  0
                                         ActionRequestValue actionRequest = (ActionRequestValue) iter.next();
 438  0
                                         if (KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ.equals(actionRequest.getActionRequested())) {
 439  0
                                                 markFinalized = false;
 440  
                                         }
 441  0
                                 }
 442  0
                                 if (markFinalized) {
 443  0
                                         document.markDocumentFinalized();
 444  
                                         // saveDocument(context);
 445  0
                                         this.notifyPostProcessor(context, event);
 446  
                                 }
 447  
                         }
 448  
                 }
 449  0
                 saveDocument(context);
 450  0
                 return document;
 451  
         }
 452  
 
 453  
         /**
 454  
          * Check the default approval policy for the document. If the default
 455  
          * approval policy is no and no approval action requests have been created
 456  
          * then throw an execption so that the document will get thrown into
 457  
          * exception routing.
 458  
          *
 459  
          * @param rh
 460  
          *            route header to be checked
 461  
          * @param docType
 462  
          *            docType of the routeHeader to be checked.
 463  
          * @throws RouteManagerException
 464  
          */
 465  
         private void checkDefaultApprovalPolicy(DocumentRouteHeaderValue document) throws RouteManagerException {
 466  0
                 if (!document.getDocumentType().getDefaultApprovePolicy().getPolicyValue().booleanValue()) {
 467  0
                         LOG.debug("Checking if any requests have been generated for the document");
 468  0
                         List requests = KEWServiceLocator.getActionRequestService().findAllActionRequestsByDocumentId(document.getDocumentId());
 469  0
                         boolean approved = false;
 470  0
                         for (Iterator iter = requests.iterator(); iter.hasNext();) {
 471  0
                                 ActionRequestValue actionRequest = (ActionRequestValue) iter.next();
 472  0
                                 if (actionRequest.isApproveOrCompleteRequest() && actionRequest.isDone()) { // &&
 473  
                                                                                                                                                                                         // !(actionRequest.getRouteMethodName().equals(KEWConstants.ADHOC_ROUTE_MODULE_NAME)
 474  
                                                                                                                                                                                         // &&
 475  
                                                                                                                                                                                         // actionRequest.isReviewerUser()
 476  
                                                                                                                                                                                         // &&
 477  
                                                                                                                                                                                         // document.getInitiatorWorkflowId().equals(actionRequest.getWorkflowId())))
 478  
                                                                                                                                                                                         // {
 479  0
                                         LOG.debug("Found at least one processed approve request so document can be approved");
 480  0
                                         approved = true;
 481  0
                                         break;
 482  
                                 }
 483  0
                         }
 484  0
                         if (!approved) {
 485  0
                                 LOG.debug("Document requires at least one request and none are present");
 486  
                                 // TODO what route method name to pass to this?
 487  0
                                 throw new RouteManagerException("Document should have generated at least one approval request.");
 488  
                         }
 489  
                 }
 490  0
         }
 491  
 
 492  
         private DocumentRouteHeaderValue notifyPostProcessor(RouteContext context, DocumentRouteStatusChange event) {
 493  0
                 DocumentRouteHeaderValue document = context.getDocument();
 494  0
                 if (context.isSimulation()) {
 495  0
                         return document;
 496  
                 }
 497  0
                 if (hasContactedPostProcessor(context, event)) {
 498  0
                         return document;
 499  
                 }
 500  0
                 String documentId = event.getDocumentId();
 501  0
                 PerformanceLogger performanceLogger = new PerformanceLogger(documentId);
 502  0
                 ProcessDocReport processReport = null;
 503  0
                 PostProcessor postProc = null;
 504  
         try {
 505  
             // use the document's post processor unless specified by the runPostProcessorLogic not to
 506  0
             if (!isRunPostProcessorLogic()) {
 507  0
                 postProc = new DefaultPostProcessor();
 508  
             } else {
 509  0
                 postProc = document.getDocumentType().getPostProcessor();
 510  
             }
 511  0
         } catch (Exception e) {
 512  0
             LOG.error("Error retrieving PostProcessor for document " + document.getDocumentId(), e);
 513  0
             throw new RouteManagerException("Error retrieving PostProcessor for document " + document.getDocumentId(), e);
 514  0
         }
 515  
                 try {
 516  0
                         processReport = postProc.doRouteStatusChange(event);
 517  0
                 } catch (Exception e) {
 518  0
                         LOG.error("Error notifying post processor", e);
 519  0
                         throw new RouteManagerException(KEWConstants.POST_PROCESSOR_FAILURE_MESSAGE, e);
 520  
                 } finally {
 521  0
                         performanceLogger.log("Time to notifyPostProcessor of event " + event.getDocumentEventCode() + ".");
 522  0
                 }
 523  
 
 524  0
                 if (!processReport.isSuccess()) {
 525  0
                         LOG.warn("PostProcessor failed to process document: " + processReport.getMessage());
 526  0
                         throw new RouteManagerException(KEWConstants.POST_PROCESSOR_FAILURE_MESSAGE + processReport.getMessage());
 527  
                 }
 528  0
                 return document;
 529  
         }
 530  
 
 531  
         /**
 532  
          * Returns true if the post processor has already been contacted about a
 533  
          * PROCESSED or FINAL post processor change. If the post processor has not
 534  
          * been contacted, this method will record on the document that it has been.
 535  
          *
 536  
          * This is because, in certain cases, a document could end up in exception
 537  
          * routing after it has already gone PROCESSED or FINAL (i.e. on Mass Action
 538  
          * processing) and we don't want to re-contact the post processor in these
 539  
          * cases.
 540  
          */
 541  
         private boolean hasContactedPostProcessor(RouteContext context, DocumentRouteStatusChange event) {
 542  
                 // get the initial node instance, the root branch is where we will store
 543  
                 // the state
 544  0
                 Branch rootBranch = context.getDocument().getRootBranch();
 545  0
                 String key = null;
 546  0
                 if (KEWConstants.ROUTE_HEADER_PROCESSED_CD.equals(event.getNewRouteStatus())) {
 547  0
                         key = KEWConstants.POST_PROCESSOR_PROCESSED_KEY;
 548  0
                 } else if (KEWConstants.ROUTE_HEADER_FINAL_CD.equals(event.getNewRouteStatus())) {
 549  0
                         key = KEWConstants.POST_PROCESSOR_FINAL_KEY;
 550  
                 } else {
 551  0
                         return false;
 552  
                 }
 553  0
                 BranchState branchState = null;
 554  0
                 if (rootBranch != null) {
 555  0
                     branchState = rootBranch.getBranchState(key);
 556  
                 } else {
 557  0
                     return false;
 558  
                 }
 559  0
                 if (branchState == null) {
 560  0
                         branchState = new BranchState();
 561  0
                         branchState.setKey(key);
 562  0
                         branchState.setValue("true");
 563  0
                         rootBranch.addBranchState(branchState);
 564  0
                         saveBranch(context, rootBranch);
 565  0
                         return false;
 566  
                 }
 567  0
                 return "true".equals(branchState.getValue());
 568  
         }
 569  
 
 570  
         /**
 571  
          * TODO in some cases, someone may modify the route header in the post
 572  
          * processor, if we don't save before and reload after we will get an
 573  
          * optimistic lock exception, we need to work on a better solution for this!
 574  
          * TODO get the routeContext in this method - it should be a better object
 575  
          * than the nodeInstance
 576  
          */
 577  
         private DocumentRouteHeaderValue notifyPostProcessor(DocumentRouteHeaderValue document, RouteNodeInstance nodeInstance, DocumentRouteLevelChange event) {
 578  0
                 getRouteHeaderService().saveRouteHeader(document);
 579  0
                 ProcessDocReport report = null;
 580  
                 try {
 581  0
                 PostProcessor postProcessor = null;
 582  
                 // use the document's post processor unless specified by the runPostProcessorLogic not to
 583  0
                 if (!isRunPostProcessorLogic()) {
 584  0
                     postProcessor = new DefaultPostProcessor();
 585  
                 } else {
 586  0
                     postProcessor = document.getDocumentType().getPostProcessor();
 587  
                 }
 588  0
                         report = postProcessor.doRouteLevelChange(event);
 589  0
                 } catch (Exception e) {
 590  0
                         LOG.warn("Problems contacting PostProcessor", e);
 591  0
                         throw new RouteManagerException("Problems contacting PostProcessor:  " + e.getMessage());
 592  0
                 }
 593  0
                 document = getRouteHeaderService().getRouteHeader(document.getDocumentId());
 594  0
                 if (!report.isSuccess()) {
 595  0
                         LOG.error("PostProcessor rejected route level change::" + report.getMessage(), report.getProcessException());
 596  0
                         throw new RouteManagerException("Route Level change failed in post processor::" + report.getMessage());
 597  
                 }
 598  0
                 return document;
 599  
         }
 600  
 
 601  
     /**
 602  
      * TODO get the routeContext in this method - it should be a better object
 603  
      * than the nodeInstance
 604  
      */
 605  
         private DocumentRouteHeaderValue notifyPostProcessorBeforeProcess(DocumentRouteHeaderValue document, Long nodeInstanceId) {
 606  0
             return notifyPostProcessorBeforeProcess(document, nodeInstanceId, new BeforeProcessEvent(document.getDocumentId(),document.getAppDocId(),nodeInstanceId));
 607  
         }
 608  
 
 609  
     /**
 610  
      * TODO get the routeContext in this method - it should be a better object
 611  
      * than the nodeInstance
 612  
      */
 613  
     private DocumentRouteHeaderValue notifyPostProcessorBeforeProcess(DocumentRouteHeaderValue document, Long nodeInstanceId, BeforeProcessEvent event) {
 614  0
         ProcessDocReport report = null;
 615  
         try {
 616  0
             PostProcessor postProcessor = null;
 617  
             // use the document's post processor unless specified by the runPostProcessorLogic not to
 618  0
             if (!isRunPostProcessorLogic()) {
 619  0
                 postProcessor = new DefaultPostProcessor();
 620  
             } else {
 621  0
                 postProcessor = document.getDocumentType().getPostProcessor();
 622  
             }
 623  0
             report = postProcessor.beforeProcess(event);
 624  0
         } catch (Exception e) {
 625  0
             LOG.warn("Problems contacting PostProcessor", e);
 626  0
             throw new RouteManagerException("Problems contacting PostProcessor:  " + e.getMessage());
 627  0
         }
 628  0
         document = getRouteHeaderService().getRouteHeader(document.getDocumentId());
 629  0
         if (!report.isSuccess()) {
 630  0
             LOG.error("PostProcessor rejected route level change::" + report.getMessage(), report.getProcessException());
 631  0
             throw new RouteManagerException("Route Level change failed in post processor::" + report.getMessage());
 632  
         }
 633  0
         return document;
 634  
     }
 635  
 
 636  
     protected void lockAdditionalDocuments(DocumentRouteHeaderValue document) throws Exception {
 637  0
                 DocumentLockingEvent lockingEvent = new DocumentLockingEvent(document.getDocumentId(), document.getAppDocId());
 638  
                 // TODO this shows up in a few places and could totally be extracted to a method
 639  0
                 PostProcessor postProcessor = null;
 640  
         // use the document's post processor unless specified by the runPostProcessorLogic not to
 641  0
         if (!isRunPostProcessorLogic()) {
 642  0
             postProcessor = new DefaultPostProcessor();
 643  
         } else {
 644  0
             postProcessor = document.getDocumentType().getPostProcessor();
 645  
         }
 646  0
         List<String> documentIdsToLock = postProcessor.getDocumentIdsToLock(lockingEvent);
 647  0
         if (documentIdsToLock != null && !documentIdsToLock.isEmpty()) {
 648  0
                 for (String documentId : documentIdsToLock) {
 649  0
                         if ( LOG.isInfoEnabled() ) {
 650  0
                                     LOG.info("Aquiring additional lock on document " + documentId);
 651  
                             }
 652  0
                         getRouteHeaderService().lockRouteHeader(documentId, true);
 653  0
                         if ( LOG.isInfoEnabled() ) {
 654  0
                                 LOG.info("Aquired lock on document " + documentId);
 655  
                         }
 656  
                 }
 657  
         }
 658  0
         }
 659  
 
 660  
     /**
 661  
      * TODO get the routeContext in this method - it should be a better object
 662  
      * than the nodeInstance
 663  
      */
 664  
     private DocumentRouteHeaderValue notifyPostProcessorAfterProcess(DocumentRouteHeaderValue document, Long nodeInstanceId, boolean successfullyProcessed) {
 665  0
             if (document == null) {
 666  
                     // this could happen if we failed to acquire the lock on the document
 667  0
                     return null;
 668  
             }
 669  0
         return notifyPostProcessorAfterProcess(document, nodeInstanceId, new AfterProcessEvent(document.getDocumentId(),document.getAppDocId(),nodeInstanceId,successfullyProcessed));
 670  
     }
 671  
 
 672  
     /**
 673  
      * TODO get the routeContext in this method - it should be a better object
 674  
      * than the nodeInstance
 675  
      */
 676  
     private DocumentRouteHeaderValue notifyPostProcessorAfterProcess(DocumentRouteHeaderValue document, Long nodeInstanceId, AfterProcessEvent event) {
 677  0
         ProcessDocReport report = null;
 678  
         try {
 679  0
             PostProcessor postProcessor = null;
 680  
             // use the document's post processor unless specified by the runPostProcessorLogic not to
 681  0
             if (!isRunPostProcessorLogic()) {
 682  0
                 postProcessor = new DefaultPostProcessor();
 683  
             } else {
 684  0
                 postProcessor = document.getDocumentType().getPostProcessor();
 685  
             }
 686  0
             report = postProcessor.afterProcess(event);
 687  0
         } catch (Exception e) {
 688  0
             LOG.warn("Problems contacting PostProcessor", e);
 689  0
             throw new RouteManagerException("Problems contacting PostProcessor:  " + e.getMessage());
 690  0
         }
 691  0
         document = getRouteHeaderService().getRouteHeader(document.getDocumentId());
 692  0
         if (!report.isSuccess()) {
 693  0
             LOG.error("PostProcessor rejected route level change::" + report.getMessage(), report.getProcessException());
 694  0
             throw new RouteManagerException("Route Level change failed in post processor::" + report.getMessage());
 695  
         }
 696  0
         return document;
 697  
     }
 698  
 
 699  
         /**
 700  
          * This method initializes the document by materializing and activating the
 701  
          * first node instance on the document.
 702  
          */
 703  
         public void initializeDocument(DocumentRouteHeaderValue document) {
 704  
                 // we set up a local route context here just so that we are able to
 705  
                 // utilize the saveNode method at the end of
 706  
                 // this method. Incidentally, this was changed from pulling the existing
 707  
                 // context out because it would override
 708  
                 // the document in the route context in the case of a document being
 709  
                 // initialized for reporting purposes.
 710  0
                 RouteContext context = new RouteContext();
 711  0
                 context.setDocument(document);
 712  0
                 if (context.getEngineState() == null) {
 713  0
                         context.setEngineState(new EngineState());
 714  
                 }
 715  0
                 Process process = document.getDocumentType().getPrimaryProcess();
 716  0
                 if (process == null || process.getInitialRouteNode() == null) {
 717  0
                     if (process == null) {
 718  0
                         throw new IllegalArgumentException("DocumentType '" + document.getDocumentType().getName() + "' has no primary process configured!");
 719  
                     }
 720  0
                         return;
 721  
                 }
 722  0
                 RouteNodeInstance nodeInstance = helper.getNodeFactory().createRouteNodeInstance(document.getDocumentId(), process.getInitialRouteNode());
 723  0
                 nodeInstance.setActive(true);
 724  0
                 helper.getNodeFactory().createBranch(KEWConstants.PRIMARY_BRANCH_NAME, null, nodeInstance);
 725  0
                 document.getInitialRouteNodeInstances().add(nodeInstance);
 726  0
                 saveNode(context, nodeInstance);
 727  0
         }
 728  
 
 729  
     private boolean isRunawayProcessDetected(EngineState engineState) throws NumberFormatException {
 730  0
             String maxNodesConstant = getParameterService().getParameterValueAsString(KEWConstants.KEW_NAMESPACE, KNSConstants.DetailTypes.ALL_DETAIL_TYPE, KEWConstants.MAX_NODES_BEFORE_RUNAWAY_PROCESS);
 731  0
             int maxNodes = (org.apache.commons.lang.StringUtils.isEmpty(maxNodesConstant)) ? 50 : Integer.valueOf(maxNodesConstant);
 732  0
             return engineState.getCompleteNodeInstances().size() > maxNodes;
 733  
         }
 734  
 
 735  
     protected RouteNodeService getRouteNodeService() {
 736  0
                 return routeNodeService;
 737  
         }
 738  
 
 739  
         protected RouteHeaderService getRouteHeaderService() {
 740  0
                 return routeHeaderService;
 741  
         }
 742  
 
 743  
     protected ParameterService getParameterService() {
 744  0
                 return parameterService;
 745  
         }
 746  
 
 747  
     public void setRouteNodeService(RouteNodeService routeNodeService) {
 748  0
         this.routeNodeService = routeNodeService;
 749  0
     }
 750  
 
 751  
     public void setRouteHeaderService(RouteHeaderService routeHeaderService) {
 752  0
         this.routeHeaderService = routeHeaderService;
 753  0
     }
 754  
 
 755  
     public void setParameterService(ParameterService parameterService) {
 756  0
         this.parameterService = parameterService;
 757  0
     }
 758  
 }