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