View Javadoc
1   /**
2    * Copyright 2005-2016 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.krad.maintenance;
17  
18  import org.apache.commons.lang.ObjectUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.kuali.rice.core.api.CoreApiServiceLocator;
21  import org.kuali.rice.core.api.util.RiceKeyConstants;
22  import org.kuali.rice.kew.api.WorkflowDocument;
23  import org.kuali.rice.krad.exception.KualiExceptionIncident;
24  import org.kuali.rice.krad.exception.ValidationException;
25  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
26  import org.kuali.rice.krad.util.GlobalVariables;
27  import org.kuali.rice.krad.util.KRADConstants;
28  import org.kuali.rice.krad.util.LegacyUtils;
29  import org.kuali.rice.krad.util.UrlFactory;
30  
31  import java.util.HashMap;
32  import java.util.Map;
33  import java.util.Properties;
34  import java.util.concurrent.Executors;
35  
36  /**
37   * Provides static utility methods for use within the maintenance framework
38   *
39   * @author Kuali Rice Team (rice.collab@kuali.org)
40   */
41  public class MaintenanceUtils {
42      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MaintenanceUtils.class);
43  
44      /**
45       * Determines if there is another maintenance document that has a lock on the same key as the given document, and
46       * therefore will block the maintenance document from being submitted
47       *
48       * @param document - maintenance document instance to check locking for
49       * @param throwExceptionIfLocked - indicates if an exception should be thrown in the case of found locking document,
50       * if false only an error will be added
51       */
52      public static void checkForLockingDocument(MaintenanceDocument document, final boolean throwExceptionIfLocked) {
53          LOG.info("starting checkForLockingDocument (by MaintenanceDocument)");
54  
55          // get the docHeaderId of the blocking docs, if any are locked and blocking
56          //String blockingDocId = getMaintenanceDocumentService().getLockingDocumentId(document);
57          final String blockingDocId = document.getNewMaintainableObject().getLockingDocumentId();
58  
59          Maintainable maintainable = (Maintainable) ObjectUtils.defaultIfNull(document.getOldMaintainableObject(), document.getNewMaintainableObject());
60          checkDocumentBlockingDocumentId(blockingDocId, throwExceptionIfLocked);
61      }
62  
63      public static void checkDocumentBlockingDocumentId(String blockingDocId, boolean throwExceptionIfLocked) {
64          // if we got nothing, then no docs are blocking, and we're done
65          if (StringUtils.isBlank(blockingDocId)) {
66              return;
67          }
68  
69          if (MaintenanceUtils.LOG.isInfoEnabled()) {
70              MaintenanceUtils.LOG.info("Locking document found:  docId = " + blockingDocId + ".");
71          }
72  
73          // load the blocking locked document
74          WorkflowDocument lockedDocument = null;
75          try {
76              // need to perform this check to prevent an exception from being thrown by the
77              // createWorkflowDocument call - the throw itself causes transaction rollback problems to
78              // occur, even though the exception would be caught here
79              if (KRADServiceLocatorWeb.getWorkflowDocumentService().workflowDocumentExists(blockingDocId)) {
80                  lockedDocument = KRADServiceLocatorWeb.getWorkflowDocumentService()
81                          .loadWorkflowDocument(blockingDocId, GlobalVariables.getUserSession().getPerson());
82              }
83          } catch (Exception ex) {
84              // clean up the lock and notify the admins
85              MaintenanceUtils.LOG.error("Unable to retrieve locking document specified in the maintenance lock table: " +
86                      blockingDocId, ex);
87  
88              cleanOrphanLocks(blockingDocId, ex);
89              return;
90          }
91          if (lockedDocument == null) {
92              MaintenanceUtils.LOG.warn("Locking document header for " + blockingDocId + "came back null.");
93              cleanOrphanLocks(blockingDocId, null);
94          }
95  
96          // if we can ignore the lock (see method notes), then exit cause we're done
97          if (lockCanBeIgnored(lockedDocument)) {
98              return;
99          }
100 
101         // build the link URL for the blocking document
102         Properties parameters = new Properties();
103         parameters.put(KRADConstants.PARAMETER_DOC_ID, blockingDocId);
104         parameters.put(KRADConstants.PARAMETER_COMMAND, KRADConstants.METHOD_DISPLAY_DOC_SEARCH_VIEW);
105         String blockingUrl = UrlFactory.parameterizeUrl(
106                 CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(
107                         KRADConstants.WORKFLOW_URL_KEY) +
108                         "/" + KRADConstants.DOC_HANDLER_ACTION, parameters);
109         if (MaintenanceUtils.LOG.isDebugEnabled()) {
110             MaintenanceUtils.LOG.debug("blockingUrl = '" + blockingUrl + "'");
111             MaintenanceUtils.LOG.debug("Maintenance record: " + lockedDocument.getApplicationDocumentId() + "is locked.");
112         }
113         String[] errorParameters = {blockingUrl, blockingDocId};
114 
115         // If specified, add an error to the ErrorMap and throw an exception; otherwise, just add a warning to the ErrorMap instead.
116         if (throwExceptionIfLocked) {
117             // post an error about the locked document
118             GlobalVariables.getMessageMap()
119                     .putError(KRADConstants.GLOBAL_ERRORS, RiceKeyConstants.ERROR_MAINTENANCE_LOCKED, errorParameters);
120             throw new ValidationException("Maintenance Record is locked by another document.");
121         } else {
122             // Post a warning about the locked document.
123             GlobalVariables.getMessageMap()
124                     .putWarning(KRADConstants.GLOBAL_MESSAGES, RiceKeyConstants.WARNING_MAINTENANCE_LOCKED,
125                             errorParameters);
126         }
127     }
128 
129     /**
130      * Guesses whether the current user should be allowed to change a document even though it is locked. It
131      * probably should use Authorization instead? See KULNRVSYS-948
132      *
133      * @param lockedDocument
134      * @return true if the document lock can be ignored
135      *
136      */
137     private static boolean lockCanBeIgnored(WorkflowDocument lockedDocument) {
138         // TODO: implement real authorization for Maintenance Document Save/Route - KULNRVSYS-948
139         if (lockedDocument == null) {
140             return true;
141         }
142 
143         // get the user-id. if no user-id, then we can do this test, so exit
144         String userId = GlobalVariables.getUserSession().getPrincipalId().trim();
145         if (StringUtils.isBlank(userId)) {
146             return false; // dont bypass locking
147         }
148 
149         // if the current user is not the initiator of the blocking document
150         if (!userId.equalsIgnoreCase(lockedDocument.getInitiatorPrincipalId().trim())) {
151             return false;
152         }
153 
154         // if the blocking document hasn't been routed, we can ignore it
155         return lockedDocument.isInitiated();
156     }
157 
158     protected static void cleanOrphanLocks(String lockingDocumentNumber, Exception workflowException) {
159         // put a try/catch around the whole thing - the whole reason we are doing this is to prevent data errors
160         // from stopping a document
161         try {
162             // delete the locks for this document since it does not seem to exist
163             KRADServiceLocatorWeb.getMaintenanceDocumentService().deleteLocks(lockingDocumentNumber);
164             // notify the incident list
165             Map<String, String> parameters = new HashMap<String, String>(1);
166             parameters.put(KRADConstants.PARAMETER_DOC_ID, lockingDocumentNumber);
167             KualiExceptionIncident kei = KRADServiceLocatorWeb.getKualiExceptionIncidentService()
168                     .getExceptionIncident(workflowException, parameters);
169             KRADServiceLocatorWeb.getKualiExceptionIncidentService().report(kei);
170         } catch (Exception ex) {
171             MaintenanceUtils.LOG.error("Unable to delete and notify upon locking document retrieval failure.", ex);
172         }
173     }
174 
175    /**
176     * Determines if the maintenance document action creates a new record.
177     *
178     * <p>
179     * When taking an action on a maintenance document, some actions cause the creation of a new record, while some don't.
180     * For example, editing does not create a record, but copying does.
181     * @param maintenanceAction
182     * @return boolean
183     * </p>
184     */
185     public static boolean isMaintenanceDocumentCreatingNewRecord(String maintenanceAction) {
186         if (KRADConstants.MAINTENANCE_EDIT_ACTION.equalsIgnoreCase(maintenanceAction)) {
187             return false;
188         } else if (KRADConstants.MAINTENANCE_NEWWITHEXISTING_ACTION.equalsIgnoreCase(maintenanceAction)) {
189             return false;
190         } else if (KRADConstants.MAINTENANCE_DELETE_ACTION.equalsIgnoreCase(maintenanceAction)) {
191             return false;
192         } else if (KRADConstants.MAINTENANCE_NEW_ACTION.equalsIgnoreCase(maintenanceAction)) {
193             return true;
194         } else if (KRADConstants.MAINTENANCE_COPY_ACTION.equalsIgnoreCase(maintenanceAction)) {
195             return true;
196         } else {
197             return true;
198         }
199     }
200 }