Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2005-2013 The Kuali Foundation Licensed under the Educational Community License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.opensource.org/licenses/ecl2.php Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.kuali.rice.kew.engine.node;
 
 
 import java.util.List;


A node which will iteratively activate any requests pending on it. Subclasses are responsible for generating the requests to be activated, and then delegating to superclass process(org.kuali.rice.kew.engine.RouteContext,org.kuali.rice.kew.engine.RouteHelper) to activate those requests. This node can be used to serve multiple batches of requests, and can be re-entered multiple times. The algorithm it implements is:
  1. activate any existing requests (requests may have been generated by an external party)
  2. while request fulfillment criteria indicates that any pending requests have been satisfied
    1. generate new requests
    2. if no requests were generated, we are done, return and transition
    3. otherwise if requests were generated
      1. activate requests (depending on activation policy, serial or parallel, NOT ALL GENERATED REQUESTS MAY BE ACTIVATED AT THIS POINT)
      2. determine a request fulfillment criteria
      3. continue in loop
  3. otherwise if pending requests have not been satisfied, block until invoked again
This node transitions/completes when there are no remaining blocking action requests (i.e., no approval or completion requests).

Author(s):
Kuali Rice Team (rice.collab@kuali.org)
 
 public class IteratedRequestActivationNode implements SimpleNode {
 
     protected final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(getClass());
     private static long generatedRequestPriority = 0;
 
     protected static interface RequestFulfillmentCriteria {
         public boolean pendingRequestsAreFulfilled(boolean activatedBlockingRequestsRouteContext routeContext);
     }
 
     private static class AllBlockingRequestsCompleteCriteria implements RequestFulfillmentCriteria {
         public boolean pendingRequestsAreFulfilled(boolean activatedBlockingRequestsRouteContext routeContext) {
             // determine whether there are any pending blocking requests
             if (activatedBlockingRequests) {
                 // if we just activated blocking requests then surely there are pending blocking requests
                 assert(activatedBlockingRequests == blockingRequestsArePending(routeContext.getDocument(), routeContext.getNodeInstance())) : "Blocking requests were activated but none were subsequently found";
                 return false;
             } else {
                 // otherwise let's see if there are any pre-existing blocking requests associated with this node instance
                 return !blockingRequestsArePending(routeContext.getDocument(), routeContext.getNodeInstance());
             }
         }
     }
 
     private static class SimulatingCriteria implements RequestFulfillmentCriteria {
         public boolean pendingRequestsAreFulfilled(boolean activatedBlockingRequestsRouteContext routeContext) {
             // when simulating, never block for requests to be fulfilled
             return true;
         }
     }
 
     public SimpleResult process(RouteContext routeContextRouteHelper routeHelperthrows Exception {
         // if previous requests were satisfied (if no requests have been generated yet, this should return true
         RequestFulfillmentCriteria criteria = getRequestFulfillmentCriteria(routeContext);
         // generate new requests until they are not satisfied or none are generated
         // if none are generated then we should transition immediately
         boolean activatedBlockingRequests = activateRequests(routeContext); // activation should always occur as something might have generated unactived requests
         boolean initialRequestGeneration = routeContext.getNodeInstance().isInitial();
        while (criteria.pendingRequestsAreFulfilled(activatedBlockingRequestsrouteContext)) {
            boolean newRequestsGenerated = generateNewRequests(initialRequestGenerationrouteContextrouteHelper);
            initialRequestGeneration = false;
            if (!newRequestsGenerated) {
                // if the pending requests were fulfilled
                // ...and we didn't generate any new requests
                // ...then there are no further requests to activate (XXX: WRONG)
                // ...and we have no more processing to do
                return new SimpleResult(true);
            }
            // activate any requests that were generated
            activatedBlockingRequests = activateRequests(routeContext);
            // set the request fulfillment criteria for the new set of requests
            // if we are simulating, always set a criteria that indicates fulfillment
            if (routeContext.isSimulation()) {
                criteria = new SimulatingCriteria();
            } else {
                criteria = getRequestFulfillmentCriteria(routeContext);
            }
        }
        // if we got here, then for some reason pending requests have not been fulfilled
        // so wait/block for request fulfillment
        return new SimpleResult(false);
    }

    
Template method that subclasses should override to indicate when activated requests have been fulfilled. The default implementation is that all pending blocking requests must be fulfilled.

Returns:
a RequestFulfillmentCriteria that indicates when activated requests have been fulfilled.
        return new AllBlockingRequestsCompleteCriteria();
    }

    
Template method that subclasses should override to generates new requests

Parameters:
initial whether this is the very first request generation, that is, the first generation in the first invocation of the node
Returns:
whether new requests were generated
Throws:
java.lang.Exception
    protected boolean generateNewRequests(boolean initialRouteContext contextRouteHelper routeHelperthrows WorkflowExceptionException {
        return false;
    }

    
Activates any pending requests and returns whether there are outstanding blocking requests

Parameters:
context the RouteContext
Returns:
whether there are outstanding blocking requests
Throws:
org.kuali.rice.kew.api.exception.WorkflowException if anything goes wrong...
    protected boolean activateRequests(RouteContext routeContextthrows WorkflowException {
        DocumentRouteHeaderValue document = routeContext.getDocument();
        RouteNodeInstance nodeInstance = routeContext.getNodeInstance();
        if (routeContext.isSimulation()) {
            // this seems to indicate whether, when we are simulating, to activate requests...
            if (routeContext.getActivationContext().isActivateRequests()) {
                activateRequests(routeContextdocumentnodeInstance);
            }
            // if we are in simulation, don't block, just transition out
            return false;
        } else {
            // activate any unactivated pending requests on this node instance
            return activateRequests(routeContextdocumentnodeInstance);
        }
    }

    

Returns:
whether there are any pending requests at the given route node instance which are blocking (i.e., 'approve' or 'complete')
    private static boolean blockingRequestsArePending(DocumentRouteHeaderValue documentRouteNodeInstance nodeInstance) {
        // returns blocking requests that are *activated*
        List<ActionRequestValuerequests = KEWServiceLocator.getActionRequestService().findPendingRootRequestsByDocIdAtRouteNode(document.getDocumentId(), nodeInstance.getRouteNodeInstanceId());
        boolean blockingRequestsArePending = false;
        for (ActionRequestValue requestrequests) {
            if (request.isApproveOrCompleteRequest()) {
                blockingRequestsArePending = true;
                break;
            }
        }
        return blockingRequestsArePending;
    }

    
Activates the action requests that are pending at this routelevel of the document. The requests are processed by priority and then request ID. It is implicit in the access that the requests are activated according to the route level above all.

FYI and acknowledgement requests do not cause the processing to stop. Only action requests for approval or completion cause the processing to stop and then only for route level with a serialized activation policy. Only requests at the current document's current route level are activated. Inactive requests at a lower level cause a routing exception.

Exception routing and adhoc routing are processed slightly differently.

Parameters:
context the RouteContext
document the document we are processing
nodeInstance the node instance we are processing
Returns:
True if the any blocking actions requests (approve or complete) were activated.
Throws:
org.kuali.rice.kew.api.exception.ResourceUnavailableException
org.kuali.rice.kew.api.exception.WorkflowException
    private boolean activateRequests(RouteContext contextDocumentRouteHeaderValue documentRouteNodeInstance nodeInstancethrows WorkflowException {
        MDC.put("docId"document.getDocumentId());
        PerformanceLogger performanceLogger = new PerformanceLogger(document.getDocumentId());
        List generatedActionItems = new ArrayList();
        List<ActionRequestValuerequests = KEWServiceLocator.getActionRequestService().findPendingRootRequestsByDocIdAtRouteNode(document.getDocumentId(), nodeInstance.getRouteNodeInstanceId());
        if (context.isSimulation()) {
            requests.addAll(context.getEngineState().getGeneratedRequests());
        }
        // this will sort higher priority requests to the front
        // blocking requests are higher priority, so all blocking requests will be
        // activated before non-blocking requests
        Collections.sort(requestsnew Utilities.PrioritySorter());
        .info("Pending Root Requests " + requests.size());
        String activationType = nodeInstance.getRouteNode().getActivationType();
        boolean isParallel = ..equals(activationType);
        boolean activatedApproveRequest = false;
        for (Iterator iter = requests.iterator(); iter.hasNext();) {
            if (activatedApproveRequest && !isParallel) {
                .info("Already activated an apprve request and serial, so not activating any more");
                break;
            }
            ActionRequestValue request = (ActionRequestValueiter.next();
            .info("ActionRequestValue: " + request);
            if (request.getParentActionRequest() != null || request.getNodeInstance() == null) {
                // 1. disregard request if it's not a top-level request
                // 2. disregard request if it's a "future" request and hasn't been attached to a node instance yet
                continue
            }
            if (request.isActive()) {
                activatedApproveRequest = activatedApproveRequest || request.isApproveOrCompleteRequest();
                continue;
            }
            logProcessingMessage(request);   
            .info("Activating request. " + request);
            activatedApproveRequest = activateRequest(contextrequestnodeInstancegeneratedActionItems) || activatedApproveRequest;
        }
        // now let's send notifications, since this code needs to be able to activate each request individually, we need
        // to collection all action items and then notify after all have been generated
        if (!context.isSimulation()) {
            KEWServiceLocator.getNotificationService().notify(generatedActionItems);
        }
        performanceLogger.log("Time to activate requests.");
        return activatedApproveRequest;
    }
    private boolean activateRequest(RouteContext contextActionRequestValue actionRequestRouteNodeInstance nodeInstanceList generatedActionItems) {
        if (actionRequest.isRoleRequest()) {
            List actionRequests = KEWServiceLocator.getActionRequestService().findPendingRootRequestsByDocIdAtRouteNode(actionRequest.getDocumentId(), nodeInstance.getRouteNodeInstanceId());
            for (Iterator iterator = actionRequests.iterator(); iterator.hasNext();) {
                ActionRequestValue siblingRequest = (ActionRequestValueiterator.next();
                if (actionRequest.getRoleName().equals(siblingRequest.getRoleName())) {
                    generatedActionItems.addAll(KEWServiceLocator.getActionRequestService().activateRequestNoNotification(siblingRequestcontext.getActivationContext()));
                }
            }
        }
        generatedActionItems.addAll(KEWServiceLocator.getActionRequestService().activateRequestNoNotification(actionRequestcontext.getActivationContext()));
        return actionRequest.isApproveOrCompleteRequest() && ! actionRequest.isDone();
    }
    
    protected void saveActionRequest(RouteContext contextActionRequestValue actionRequest) {
        if (!context.isSimulation()) {
            KEWServiceLocator.getActionRequestService().saveActionRequest(actionRequest);
        } else {
            actionRequest.setActionRequestId(String.valueOf(++));
            context.getEngineState().getGeneratedRequests().add(actionRequest);    
        }
        
    }
    
    private void logProcessingMessage(ActionRequestValue request) {
        //if (LOG.isDebugEnabled()) {
                RouteNodeInstance nodeInstance = request.getNodeInstance();
            StringBuffer buffer = new StringBuffer();
            buffer.append("Processing AR: ").append(request.getActionRequestId()).append("\n");
            buffer.append("AR Node Name: ").append(nodeInstance != null ? nodeInstance.getName() : "null").append("\n");
            buffer.append("AR RouteLevel: ").append(request.getRouteLevel()).append("\n");
            buffer.append("AR Request Code: ").append(request.getActionRequested()).append("\n");
            buffer.append("AR Request priority: ").append(request.getPriority()).append("\n");
            .info(buffer);
        //}
    }
            
New to GrepCode? Check out our FAQ X