View Javadoc

1   /*
2    * Copyright 2005-2007 The Kuali Foundation
3    *
4    *
5    * Licensed under the Educational Community License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.opensource.org/licenses/ecl2.php
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.kuali.rice.kew.actions;
18  
19  import java.util.Collections;
20  import java.util.HashSet;
21  import java.util.Iterator;
22  import java.util.List;
23  import java.util.Set;
24  
25  import org.apache.log4j.MDC;
26  import org.kuali.rice.kew.actionrequest.ActionRequestValue;
27  import org.kuali.rice.kew.actionrequest.Recipient;
28  import org.kuali.rice.kew.actions.asyncservices.BlanketApproveProcessorService;
29  import org.kuali.rice.kew.actiontaken.ActionTakenValue;
30  import org.kuali.rice.kew.api.WorkflowRuntimeException;
31  import org.kuali.rice.kew.doctype.bo.DocumentType;
32  import org.kuali.rice.kew.engine.BlanketApproveEngine;
33  import org.kuali.rice.kew.engine.CompatUtils;
34  import org.kuali.rice.kew.engine.OrchestrationConfig;
35  import org.kuali.rice.kew.engine.OrchestrationConfig.EngineCapability;
36  import org.kuali.rice.kew.engine.RouteContext;
37  import org.kuali.rice.kew.engine.node.RouteNode;
38  import org.kuali.rice.kew.engine.node.service.RouteNodeService;
39  import org.kuali.rice.kew.exception.InvalidActionTakenException;
40  import org.kuali.rice.kew.messaging.MessageServiceNames;
41  import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
42  import org.kuali.rice.kew.service.KEWServiceLocator;
43  import org.kuali.rice.kew.util.KEWConstants;
44  import org.kuali.rice.kim.api.identity.principal.PrincipalContract;
45  
46  
47  /**
48   * Does the sync work for blanket approves requested by client apps.
49   *
50   * @author Kuali Rice Team (rice.collab@kuali.org)
51   */
52  public class BlanketApproveAction extends ActionTakenEvent {
53  
54      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BlanketApproveAction.class);
55      private Set<String> nodeNames;
56  
57      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal) {
58          super(KEWConstants.ACTION_TAKEN_BLANKET_APPROVE_CD, rh, principal);
59  
60          setQueueDocumentAfterAction(false);
61  
62      }
63  
64      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal, String annotation, Integer routeLevel) {
65          this(rh, principal, annotation, convertRouteLevel(rh.getDocumentType(), routeLevel));
66      }
67  
68      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal, String annotation, String nodeName) {
69          this(rh, principal, annotation, Collections.singleton(nodeName));
70  
71      }
72  
73      public BlanketApproveAction(DocumentRouteHeaderValue rh, PrincipalContract principal, String annotation, Set<String> nodeNames) {
74          super(KEWConstants.ACTION_TAKEN_BLANKET_APPROVE_CD, rh, principal, annotation);
75          this.nodeNames = (nodeNames == null ? new HashSet<String>() : nodeNames);
76          setQueueDocumentAfterAction(false);
77      }
78  
79      private static Set<String> convertRouteLevel(DocumentType documentType, Integer routeLevel) {
80          Set<String> nodeNames = new HashSet<String>();
81          if (routeLevel == null) {
82              return nodeNames;
83          }
84          RouteNode node = CompatUtils.getNodeForLevel(documentType, routeLevel);
85          if (node == null) {
86              throw new WorkflowRuntimeException("Could not locate a valid node for the given route level: " + routeLevel);
87          }
88          nodeNames.add(node.getRouteNodeName());
89          return nodeNames;
90      }
91  
92      /* (non-Javadoc)
93       * @see org.kuali.rice.kew.actions.ActionTakenEvent#validateActionRules()
94       */
95      @Override
96      public String validateActionRules() {
97          return validateActionRules(getActionRequestService().findAllPendingRequests(routeHeader.getDocumentId()));
98      }
99  
100     public String validateActionRules(List<ActionRequestValue> actionRequests) {
101         if ( (nodeNames != null) && (!nodeNames.isEmpty()) ) {
102             String nodeName = isGivenNodeListValid();
103             if (!org.apache.commons.lang.StringUtils.isEmpty(nodeName)) {
104                 return "Document already at or beyond route node " + nodeName;
105             }
106         }
107         if (!getRouteHeader().isValidActionToTake(getActionPerformedCode())) {
108             return "Document is not in a state to be approved";
109         }
110         List<ActionRequestValue> filteredActionRequests = filterActionRequestsByCode(actionRequests, KEWConstants.ACTION_REQUEST_COMPLETE_REQ);
111         if (!isActionCompatibleRequest(filteredActionRequests)) {
112             return "No request for the user is compatible with the BlanketApprove Action";
113         }
114     	// check state before checking kim
115         if (! KEWServiceLocator.getDocumentTypePermissionService().canBlanketApprove(getPrincipal().getPrincipalId(), getRouteHeader().getDocumentType(), getRouteHeader().getDocRouteStatus(), getRouteHeader().getInitiatorWorkflowId())) {
116             return "User is not authorized to BlanketApprove document";
117         }
118         return "";
119     }
120 
121     private String isGivenNodeListValid() {
122         for (Iterator<String> iterator = nodeNames.iterator(); iterator.hasNext();) {
123             String nodeName = (String) iterator.next();
124             if (nodeName == null) {
125                 iterator.remove();
126                 continue;
127             }
128             if (!getRouteNodeService().isNodeInPath(getRouteHeader(), nodeName)) {
129                 return nodeName;
130             }
131         }
132         return "";
133     }
134 
135     public void recordAction() throws InvalidActionTakenException {
136         MDC.put("docId", getRouteHeader().getDocumentId());
137         updateSearchableAttributesIfPossible();
138 
139         List<ActionRequestValue> actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KEWConstants.ACTION_REQUEST_COMPLETE_REQ);
140         String errorMessage = validateActionRules(actionRequests);
141         if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
142             throw new InvalidActionTakenException(errorMessage);
143         }
144 
145         LOG.debug("Checking to see if the action is legal");
146 
147             LOG.debug("Blanket approving document : " + annotation);
148 
149             if (getRouteHeader().isStateInitiated() || getRouteHeader().isStateSaved()) {
150                 markDocumentEnroute(getRouteHeader());
151                 getRouteHeader().setRoutedByUserWorkflowId(getPrincipal().getPrincipalId());
152             }
153 
154             LOG.debug("Record the blanket approval action");
155             Recipient delegator = findDelegatorForActionRequests(actionRequests);
156             ActionTakenValue actionTaken = saveActionTaken(delegator);
157 
158             LOG.debug("Deactivate pending action requests for user");
159             getActionRequestService().deactivateRequests(actionTaken, actionRequests);
160             notifyActionTaken(actionTaken);
161 
162             KEWServiceLocator.getRouteHeaderService().saveRouteHeader(getRouteHeader());
163 
164 //        } else {
165 //            LOG.warn("Document not in state to be approved.");
166 //            throw new InvalidActionTakenException("Document is not in a state to be approved");
167 //        }
168             
169           queueDeferredWork(actionTaken);
170     }
171 
172     protected void queueDeferredWork(ActionTakenValue actionTaken) {
173         try {
174         	final boolean shouldIndex = getRouteHeader().getDocumentType().hasSearchableAttributes() && RouteContext.getCurrentRouteContext().isSearchIndexingRequestedForContext();
175         	
176             BlanketApproveProcessorService blanketApprove = MessageServiceNames.getBlanketApproveProcessorService(routeHeader);
177             blanketApprove.doBlanketApproveWork(routeHeader.getDocumentId(), getPrincipal().getPrincipalId(), actionTaken.getActionTakenId(), nodeNames, shouldIndex);
178 //
179 
180 //          KEWAsyncronousJavaService blanketApproveProcessor = (KEWAsyncronousJavaService)SpringServiceLocator.getMessageHelper().getServiceAsynchronously(
181 //                  MessageServiceNames.BLANKET_APPROVE_PROCESSING_SERVICE, routeHeader);
182 //          blanketApproveProcessor.invoke(BlanketApproveProcessor.getPayLoad(user, action.getActionTaken(), nodeNames, routeHeader));
183 
184 //          SpringServiceLocator.getMessageHelper().sendMessage(MessageServiceNames.BLANKET_APPROVE_PROCESSING_SERVICE,
185 //                  BlanketApproveProcessor.getPayLoad(user, action.getActionTaken(), nodeNames, routeHeader), routeHeader);
186         } catch (Exception e) {
187             LOG.error(e);
188             throw new WorkflowRuntimeException(e);
189         }
190 //      SpringServiceLocator.getRouteQueueService().requeueDocument(routeHeader.getDocumentId(), KEWConstants.ROUTE_QUEUE_BLANKET_APPROVE_PRIORITY, new Long(0),
191 //              BlanketApproveProcessor.class.getName(), BlanketApproveProcessor.getBlanketApproveProcessorValue(user, action.getActionTaken(), nodeNames));
192     }
193     
194     public void performDeferredBlanketApproveWork(ActionTakenValue actionTaken) throws Exception {
195 
196         if (getRouteHeader().isInException()) {
197             LOG.debug("Moving document back to Enroute from Exception");
198 
199             String oldStatus = getRouteHeader().getDocRouteStatus();
200             getRouteHeader().markDocumentEnroute();
201 
202             String newStatus = getRouteHeader().getDocRouteStatus();
203             notifyStatusChange(newStatus, oldStatus);
204         }
205         OrchestrationConfig config = new OrchestrationConfig(EngineCapability.BLANKET_APPROVAL, nodeNames, actionTaken);
206         BlanketApproveEngine blanketApproveEngine = KEWServiceLocator.getWorkflowEngineFactory().newEngine(config);
207         blanketApproveEngine.process(getRouteHeader().getDocumentId(), null);
208    
209         queueDocumentProcessing();
210    }
211 
212     protected void markDocumentEnroute(DocumentRouteHeaderValue routeHeader) throws InvalidActionTakenException {
213         String oldStatus = getRouteHeader().getDocRouteStatus();
214         getRouteHeader().markDocumentEnroute();
215 
216         String newStatus = getRouteHeader().getDocRouteStatus();
217         notifyStatusChange(newStatus, oldStatus);
218         KEWServiceLocator.getRouteHeaderService().saveRouteHeader(getRouteHeader());
219     }
220 
221     private RouteNodeService getRouteNodeService() {
222         return KEWServiceLocator.getRouteNodeService();
223     }
224 }