001: /*
002: * Copyright 2005-2006 The Kuali Foundation.
003: *
004: *
005: * Licensed under the Educational Community License, Version 1.0 (the "License");
006: * you may not use this file except in compliance with the License.
007: * You may obtain a copy of the License at
008: *
009: * http://www.opensource.org/licenses/ecl1.php
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017: package edu.iu.uis.eden.engine;
018:
019: import java.util.ArrayList;
020: import java.util.HashSet;
021: import java.util.Iterator;
022: import java.util.LinkedList;
023: import java.util.List;
024: import java.util.Set;
025:
026: import org.apache.log4j.MDC;
027:
028: import edu.iu.uis.eden.EdenConstants;
029: import edu.iu.uis.eden.KEWServiceLocator;
030: import edu.iu.uis.eden.actionrequests.ActionRequestFactory;
031: import edu.iu.uis.eden.actionrequests.ActionRequestService;
032: import edu.iu.uis.eden.actionrequests.ActionRequestValue;
033: import edu.iu.uis.eden.actions.NotificationContext;
034: import edu.iu.uis.eden.actiontaken.ActionTakenValue;
035: import edu.iu.uis.eden.engine.node.Process;
036: import edu.iu.uis.eden.engine.node.RouteNode;
037: import edu.iu.uis.eden.engine.node.RouteNodeInstance;
038: import edu.iu.uis.eden.exception.EdenUserNotFoundException;
039: import edu.iu.uis.eden.exception.InvalidActionTakenException;
040: import edu.iu.uis.eden.exception.WorkflowException;
041: import edu.iu.uis.eden.routeheader.DocumentRouteHeaderValue;
042: import edu.iu.uis.eden.util.Utilities;
043:
044: /**
045: * A WorkflowEngine implementation which orchestrates the document through the blanket approval process.
046: *
047: * @author ewestfal
048: */
049: public class BlanketApproveEngine extends StandardWorkflowEngine {
050:
051: // private Set nodeNames;
052: // private ActionTakenValue actionTaken;
053: // private ActionRequestNotificationGenerator notifier = new ActionRequestNotificationGenerator();
054: private OrchestrationConfig config;
055:
056: public BlanketApproveEngine(OrchestrationConfig config) {
057: this .config = config;
058: }
059:
060: public BlanketApproveEngine(String nodeName,
061: ActionTakenValue actionTaken) {
062: this (wrapInSet(nodeName), actionTaken);
063: }
064:
065: public BlanketApproveEngine(Set nodeNames,
066: ActionTakenValue actionTaken) {
067: this (createBlanketApproveConfig(nodeNames, actionTaken));
068: }
069:
070: private static Set wrapInSet(String nodeName) {
071: Set nodeNames = new HashSet();
072: if (!Utilities.isEmpty(nodeName)) {
073: nodeNames.add(nodeName);
074: }
075: return nodeNames;
076: }
077:
078: private static OrchestrationConfig createBlanketApproveConfig(
079: Set nodeNames, ActionTakenValue actionTaken) {
080: OrchestrationConfig config = new OrchestrationConfig();
081: config.setCause(actionTaken);
082: config.setDestinationNodeNames(nodeNames);
083: config
084: .setNotificationType(EdenConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ);
085: config.setSendNotifications(true);
086: return config;
087: }
088:
089: /**
090: * Orchestrates the document through the blanket approval process. The termination of the process is keyed off of the Set of node names. If there are no node names, then the document will be blanket approved past the terminal node(s) in the document.
091: */
092: public void process(Long documentId, Long nodeInstanceId)
093: throws Exception {
094: if (documentId == null) {
095: throw new IllegalArgumentException(
096: "Cannot process a null document id.");
097: }
098: MDC.put("docID", documentId);
099: RouteContext context = RouteContext.getCurrentRouteContext();
100: try {
101: KEWServiceLocator.getRouteHeaderService().lockRouteHeader(
102: documentId, true);
103: LOG.info("Processing document for Blanket Approval: "
104: + documentId + " : " + nodeInstanceId);
105: DocumentRouteHeaderValue document = getRouteHeaderService()
106: .getRouteHeader(documentId);
107: if (!document.isRoutable()) {
108: LOG
109: .debug("Document not routable so returning with doing no action");
110: return;
111: }
112: List activeNodeInstances = new ArrayList();
113: if (nodeInstanceId == null) {
114: activeNodeInstances.addAll(getRouteNodeService()
115: .getActiveNodeInstances(documentId));
116: } else {
117: RouteNodeInstance instanceNode = getRouteNodeService()
118: .findRouteNodeInstanceById(nodeInstanceId);
119: if (instanceNode == null) {
120: throw new IllegalArgumentException(
121: "Invalid node instance id: "
122: + nodeInstanceId);
123: }
124: activeNodeInstances.add(instanceNode);
125: }
126: List nodeInstancesToProcess = determineNodeInstancesToProcess(
127: activeNodeInstances, config
128: .getDestinationNodeNames());
129:
130: context.setDoNotSendApproveNotificationEmails(true);
131: context.setDocument(document);
132: context.setEngineState(new EngineState());
133: NotificationContext notifyContext = null;
134: if (config.isSendNotifications()) {
135: notifyContext = new NotificationContext(
136: EdenConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ,
137: config.getCause().getWorkflowUser(), config
138: .getCause().getActionTaken());
139: }
140: try {
141: List processingQueue = new LinkedList();
142: for (Iterator iterator = nodeInstancesToProcess
143: .iterator(); iterator.hasNext();) {
144: processingQueue.add(new ProcessEntry(
145: (RouteNodeInstance) iterator.next()));
146: }
147: Set nodesCompleted = new HashSet();
148: // check the processingQueue for cases where there are no dest. nodes otherwise check if we've reached
149: // the dest. nodes
150: while (!processingQueue.isEmpty()
151: && !isReachedDestinationNodes(config
152: .getDestinationNodeNames(),
153: nodesCompleted)) {
154: ProcessEntry entry = (ProcessEntry) processingQueue
155: .remove(0);
156: // TODO document magical join node workage (ask Eric)
157: // TODO this has been set arbitrarily high because the implemented processing model here will probably not work for
158: // large parallel object graphs. This needs to be re-evaluated, see KULWF-459.
159: if (entry.getTimesProcessed() > 20) {
160: throw new WorkflowException(
161: "Could not process document through to blanket approval."
162: + " Document failed to progress past node "
163: + entry.getNodeInstance()
164: .getRouteNode()
165: .getRouteNodeName());
166: }
167: RouteNodeInstance nodeInstance = entry
168: .getNodeInstance();
169: context.setNodeInstance(nodeInstance);
170: if (config.getDestinationNodeNames().contains(
171: nodeInstance.getName())) {
172: nodesCompleted.add(nodeInstance.getName());
173: continue;
174: }
175: ProcessContext resultProcessContext = processNodeInstance(
176: context, helper);
177: invokeBlanketApproval(config.getCause(),
178: nodeInstance, notifyContext);
179: if (!resultProcessContext.getNextNodeInstances()
180: .isEmpty()
181: || resultProcessContext.isComplete()) {
182: for (Iterator nodeIt = resultProcessContext
183: .getNextNodeInstances().iterator(); nodeIt
184: .hasNext();) {
185: addToProcessingQueue(processingQueue,
186: (RouteNodeInstance) nodeIt.next());
187: }
188: } else {
189: entry.increment();
190: processingQueue.add(processingQueue.size(),
191: entry);
192: }
193: }
194: //clear the context so the standard engine can begin routing normally
195: RouteContext.clearCurrentRouteContext();
196: // continue with normal routing after blanket approve brings us to the correct place
197: // if there is an active approve request this is no-op.
198: super .process(documentId, null);
199: } catch (Exception e) {
200: // TODO throw a new 'RoutingException' which holds the RoutingState
201: throw new RuntimeException(e);
202: }
203: } finally {
204: RouteContext.clearCurrentRouteContext();
205: MDC.remove("docID");
206: }
207: }
208:
209: /**
210: * @return true if all destination node are active but not yet complete - ready for the standard engine to take over the activation process for requests
211: */
212: private boolean isReachedDestinationNodes(
213: Set destinationNodesNames, Set nodeNamesCompleted) {
214: return !destinationNodesNames.isEmpty()
215: && nodeNamesCompleted.equals(destinationNodesNames);
216: }
217:
218: private void addToProcessingQueue(List processingQueue,
219: RouteNodeInstance nodeInstance) {
220: // first, detect if it's already there
221: for (Iterator iterator = processingQueue.iterator(); iterator
222: .hasNext();) {
223: ProcessEntry entry = (ProcessEntry) iterator.next();
224: if (entry.getNodeInstance().getRouteNodeInstanceId()
225: .equals(nodeInstance.getRouteNodeInstanceId())) {
226: entry.setNodeInstance(nodeInstance);
227: return;
228: }
229: }
230: processingQueue.add(processingQueue.size(), new ProcessEntry(
231: nodeInstance));
232: }
233:
234: /**
235: * If there are multiple paths, we need to figure out which ones we need to follow for blanket approval. This method will throw an exception if a node with the given name could not be located in the routing path. This method is written in such a way that it should be impossible for there to be an infinite loop, even if there is extensive looping in the node graph.
236: */
237: private List determineNodeInstancesToProcess(
238: List activeNodeInstances, Set nodeNames) throws Exception {
239: if (nodeNames.isEmpty()) {
240: return activeNodeInstances;
241: }
242: List nodeInstancesToProcess = new ArrayList();
243: for (Iterator iterator = activeNodeInstances.iterator(); iterator
244: .hasNext();) {
245: RouteNodeInstance nodeInstance = (RouteNodeInstance) iterator
246: .next();
247: if (isNodeNameInPath(nodeNames, nodeInstance)) {
248: nodeInstancesToProcess.add(nodeInstance);
249: }
250: }
251: if (nodeInstancesToProcess.size() == 0) {
252: throw new InvalidActionTakenException(
253: "Could not locate nodes with the given names in the blanket approval path '"
254: + printNodeNames(nodeNames)
255: + "'. "
256: + "The document is probably already passed the specified nodes or does not contain the nodes.");
257: }
258: return nodeInstancesToProcess;
259: }
260:
261: private boolean isNodeNameInPath(Set nodeNames,
262: RouteNodeInstance nodeInstance) throws Exception {
263: boolean isInPath = false;
264: for (Iterator nodeNameIt = nodeNames.iterator(); nodeNameIt
265: .hasNext();) {
266: String nodeName = (String) nodeNameIt.next();
267: for (Iterator iterator = nodeInstance.getRouteNode()
268: .getNextNodes().iterator(); iterator.hasNext();) {
269: RouteNode nextNode = (RouteNode) iterator.next();
270: isInPath = isInPath
271: || isNodeNameInPath(nodeName, nextNode,
272: new HashSet());
273: }
274: }
275: return isInPath;
276: }
277:
278: private boolean isNodeNameInPath(String nodeName, RouteNode node,
279: Set inspected) throws Exception {
280: boolean isInPath = !inspected.contains(node.getRouteNodeId())
281: && node.getRouteNodeName().equals(nodeName);
282: inspected.add(node.getRouteNodeId());
283: if (helper.isSubProcessNode(node)) {
284: Process subProcess = node.getDocumentType()
285: .getNamedProcess(node.getRouteNodeName());
286: RouteNode subNode = subProcess.getInitialRouteNode();
287: isInPath = isInPath
288: || isNodeNameInPath(nodeName, subNode, inspected);
289: }
290: for (Iterator iterator = node.getNextNodes().iterator(); iterator
291: .hasNext();) {
292: RouteNode nextNode = (RouteNode) iterator.next();
293: isInPath = isInPath
294: || isNodeNameInPath(nodeName, nextNode, inspected);
295: }
296: return isInPath;
297: }
298:
299: private String printNodeNames(Set nodesNames) {
300: StringBuffer buffer = new StringBuffer();
301: for (Iterator iterator = nodesNames.iterator(); iterator
302: .hasNext();) {
303: String nodeName = (String) iterator.next();
304: buffer.append(nodeName);
305: buffer.append((iterator.hasNext() ? ", " : ""));
306: }
307: return buffer.toString();
308: }
309:
310: /**
311: * Invokes the blanket approval for the given node instance. This deactivates all pending approve or complete requests at the node and sends out notifications to the individuals who's requests were trumped by the blanket approve.
312: */
313: private void invokeBlanketApproval(ActionTakenValue actionTaken,
314: RouteNodeInstance nodeInstance,
315: NotificationContext notifyContext)
316: throws EdenUserNotFoundException {
317: List actionRequests = getActionRequestService()
318: .findPendingRootRequestsByDocIdAtRouteNode(
319: nodeInstance.getDocumentId(),
320: nodeInstance.getRouteNodeInstanceId());
321: actionRequests = getActionRequestService().getRootRequests(
322: actionRequests);
323: List requestsToNotify = new ArrayList();
324: for (Iterator iterator = actionRequests.iterator(); iterator
325: .hasNext();) {
326: ActionRequestValue request = (ActionRequestValue) iterator
327: .next();
328: if (request.isApproveOrCompleteRequest()) {
329: getActionRequestService().deactivateRequest(
330: actionTaken, request);
331: requestsToNotify.add(request);
332: }
333: }
334: if (notifyContext != null) {
335: ActionRequestFactory arFactory = new ActionRequestFactory(
336: RouteContext.getCurrentRouteContext().getDocument(),
337: nodeInstance);
338: List notificationRequests = arFactory
339: .generateNotifications(requestsToNotify,
340: notifyContext.getUserTakingAction(),
341: actionTaken.getDelegatorUser(),
342: notifyContext.getNotificationRequestCode(),
343: notifyContext.getActionTakenCode());
344: getActionRequestService().activateRequests(
345: notificationRequests);
346: }
347: }
348:
349: private ActionRequestService getActionRequestService() {
350: return KEWServiceLocator.getActionRequestService();
351: }
352:
353: private class ProcessEntry {
354:
355: private RouteNodeInstance nodeInstance;
356: private int timesProcessed = 0;
357:
358: public ProcessEntry(RouteNodeInstance nodeInstance) {
359: this .nodeInstance = nodeInstance;
360: }
361:
362: public RouteNodeInstance getNodeInstance() {
363: return nodeInstance;
364: }
365:
366: public void setNodeInstance(RouteNodeInstance nodeInstance) {
367: this .nodeInstance = nodeInstance;
368: }
369:
370: public void increment() {
371: timesProcessed++;
372: }
373:
374: public int getTimesProcessed() {
375: return timesProcessed;
376: }
377:
378: }
379:
380: }
|