View Javadoc

1   /**
2    * Copyright 2005-2012 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  package org.kuali.rice.kew.actions;
17  
18  import java.util.Collections;
19  import java.util.HashSet;
20  import java.util.Iterator;
21  import java.util.List;
22  import java.util.Set;
23  
24  import org.apache.log4j.MDC;
25  import org.kuali.rice.kew.actionrequest.ActionRequestValue;
26  import org.kuali.rice.kew.actionrequest.Recipient;
27  import org.kuali.rice.kew.actions.ActionTakenEvent;
28  import org.kuali.rice.kew.api.document.DocumentOrchestrationQueue;
29  import org.kuali.rice.kew.actiontaken.ActionTakenValue;
30  import org.kuali.rice.kew.api.WorkflowRuntimeException;
31  import org.kuali.rice.kew.api.document.DocumentProcessingOptions;
32  import org.kuali.rice.kew.api.exception.InvalidActionTakenException;
33  import org.kuali.rice.kew.doctype.bo.DocumentType;
34  import org.kuali.rice.kew.engine.BlanketApproveEngine;
35  import org.kuali.rice.kew.engine.CompatUtils;
36  import org.kuali.rice.kew.engine.OrchestrationConfig;
37  import org.kuali.rice.kew.engine.OrchestrationConfig.EngineCapability;
38  import org.kuali.rice.kew.engine.RouteContext;
39  import org.kuali.rice.kew.engine.node.RouteNode;
40  import org.kuali.rice.kew.engine.node.service.RouteNodeService;
41  import org.kuali.rice.kew.messaging.MessageServiceNames;
42  import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
43  import org.kuali.rice.kew.service.KEWServiceLocator;
44  import org.kuali.rice.kew.api.KewApiConstants;
45  import org.kuali.rice.kim.api.identity.principal.PrincipalContract;
46  
47  
48  /**
49   * Does the sync work for blanket approves requested by client apps.
50   *
51   * @author Kuali Rice Team (rice.collab@kuali.org)
52   */
53  public class BlanketApproveAction extends ActionTakenEvent {
54  
55      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BlanketApproveAction.class);
56      private Set<String> nodeNames;
57  
58      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal) {
59          this(rh, principal, DEFAULT_ANNOTATION, (Set<String>) null);
60      }
61  
62      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal, String annotation, Integer routeLevel) {
63          this(rh, principal, annotation, convertRouteLevel(rh.getDocumentType(), routeLevel));
64      }
65  
66      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal, String annotation, String nodeName) {
67          this(rh, principal, annotation, Collections.singleton(nodeName));
68      }
69  
70      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal, String annotation, Set<String> nodeNames) {
71          super(KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD, rh, principal, annotation, DEFAULT_RUN_POSTPROCESSOR_LOGIC, false);
72          this.nodeNames = (nodeNames == null ? new HashSet<String>() : nodeNames);
73      }
74  
75      private static Set<String> convertRouteLevel(DocumentType documentType, Integer routeLevel) {
76          Set<String> nodeNames = new HashSet<String>();
77          if (routeLevel == null) {
78              return nodeNames;
79          }
80          RouteNode node = CompatUtils.getNodeForLevel(documentType, routeLevel);
81          if (node == null) {
82              throw new WorkflowRuntimeException("Could not locate a valid node for the given route level: " + routeLevel);
83          }
84          nodeNames.add(node.getRouteNodeName());
85          return nodeNames;
86      }
87  
88      /* (non-Javadoc)
89       * @see org.kuali.rice.kew.actions.ActionTakenEvent#validateActionRules()
90       */
91      @Override
92      public String validateActionRules() {
93          return validateActionRules(getActionRequestService().findAllPendingRequests(routeHeader.getDocumentId()));
94      }
95  
96      public String validateActionRules(List<ActionRequestValue> actionRequests) {
97          if ( (nodeNames != null) && (!nodeNames.isEmpty()) ) {
98              String nodeName = isGivenNodeListValid();
99              if (!org.apache.commons.lang.StringUtils.isEmpty(nodeName)) {
100                 return "Document already at or beyond route node " + nodeName;
101             }
102         }
103         if (!getRouteHeader().isValidActionToTake(getActionPerformedCode())) {
104             return "Document is not in a state to be approved";
105         }
106         List<ActionRequestValue> filteredActionRequests = filterActionRequestsByCode(actionRequests, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ);
107         if (!isActionCompatibleRequest(filteredActionRequests)) {
108             return "No request for the user is compatible with the BlanketApprove Action";
109         }
110     	// check state before checking kim
111         if (! KEWServiceLocator.getDocumentTypePermissionService().canBlanketApprove(getPrincipal().getPrincipalId(), getRouteHeader().getDocumentType(), getRouteHeader().getDocRouteStatus(), getRouteHeader().getInitiatorWorkflowId())) {
112             return "User is not authorized to BlanketApprove document";
113         }
114         return "";
115     }
116 
117     private String isGivenNodeListValid() {
118         for (Iterator<String> iterator = nodeNames.iterator(); iterator.hasNext();) {
119             String nodeName = (String) iterator.next();
120             if (nodeName == null) {
121                 iterator.remove();
122                 continue;
123             }
124             if (!getRouteNodeService().isNodeInPath(getRouteHeader(), nodeName)) {
125                 return nodeName;
126             }
127         }
128         return "";
129     }
130 
131     public void recordAction() throws InvalidActionTakenException {
132         MDC.put("docId", getRouteHeader().getDocumentId());
133         updateSearchableAttributesIfPossible();
134 
135         List<ActionRequestValue> actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KewApiConstants.ACTION_REQUEST_COMPLETE_REQ);
136         String errorMessage = validateActionRules(actionRequests);
137         if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
138             throw new InvalidActionTakenException(errorMessage);
139         }
140 
141         LOG.debug("Checking to see if the action is legal");
142 
143             LOG.debug("Blanket approving document : " + annotation);
144 
145             if (getRouteHeader().isStateInitiated() || getRouteHeader().isStateSaved()) {
146                 markDocumentEnroute(getRouteHeader());
147                 getRouteHeader().setRoutedByUserWorkflowId(getPrincipal().getPrincipalId());
148             }
149 
150             LOG.debug("Record the blanket approval action");
151             Recipient delegator = findDelegatorForActionRequests(actionRequests);
152             ActionTakenValue actionTaken = saveActionTaken(delegator);
153 
154             LOG.debug("Deactivate pending action requests for user");
155             getActionRequestService().deactivateRequests(actionTaken, actionRequests);
156             notifyActionTaken(actionTaken);
157 
158             KEWServiceLocator.getRouteHeaderService().saveRouteHeader(getRouteHeader());
159 
160 //        } else {
161 //            LOG.warn("Document not in state to be approved.");
162 //            throw new InvalidActionTakenException("Document is not in a state to be approved");
163 //        }
164             
165           queueDeferredWork(actionTaken);
166     }
167 
168     protected void queueDeferredWork(ActionTakenValue actionTaken) {
169         try {
170         	final boolean shouldIndex = getRouteHeader().getDocumentType().hasSearchableAttributes() && RouteContext.getCurrentRouteContext().isSearchIndexingRequestedForContext();
171         	
172             DocumentOrchestrationQueue blanketApprove = MessageServiceNames.getDocumentOrchestrationQueue(routeHeader);
173             org.kuali.rice.kew.api.document.OrchestrationConfig orchestrationConfig =
174                     org.kuali.rice.kew.api.document.OrchestrationConfig.create(actionTaken.getActionTakenId(), nodeNames);
175             DocumentProcessingOptions options = DocumentProcessingOptions.create(true, shouldIndex);
176             blanketApprove.orchestrateDocument(routeHeader.getDocumentId(), getPrincipal().getPrincipalId(),
177                     orchestrationConfig, options);
178         } catch (Exception e) {
179             LOG.error(e);
180             throw new WorkflowRuntimeException(e);
181         }
182     }
183     
184     public void performDeferredBlanketApproveWork(ActionTakenValue actionTaken, DocumentProcessingOptions processingOptions) throws Exception {
185 
186         if (getRouteHeader().isInException()) {
187             LOG.debug("Moving document back to Enroute from Exception");
188 
189             markDocumentEnroute(getRouteHeader());
190 
191         }
192         OrchestrationConfig config = new OrchestrationConfig(EngineCapability.BLANKET_APPROVAL, nodeNames, actionTaken, processingOptions.isSendNotifications(), processingOptions.isRunPostProcessor());
193         BlanketApproveEngine blanketApproveEngine = KEWServiceLocator.getWorkflowEngineFactory().newEngine(config);
194         blanketApproveEngine.process(getRouteHeader().getDocumentId(), null);
195    
196         queueDocumentProcessing();
197    }
198 
199     protected void markDocumentEnroute(DocumentRouteHeaderValue routeHeader) throws InvalidActionTakenException {
200         String oldStatus = routeHeader.getDocRouteStatus();
201         routeHeader.markDocumentEnroute();
202 
203         String newStatus = routeHeader.getDocRouteStatus();
204         notifyStatusChange(newStatus, oldStatus);
205         KEWServiceLocator.getRouteHeaderService().saveRouteHeader(routeHeader);
206     }
207 
208     private RouteNodeService getRouteNodeService() {
209         return KEWServiceLocator.getRouteNodeService();
210     }
211 }