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.krad.rules;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.rice.core.api.CoreApiServiceLocator;
20  import org.kuali.rice.core.api.config.property.ConfigurationService;
21  import org.kuali.rice.core.api.datetime.DateTimeService;
22  import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
23  import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
24  import org.kuali.rice.core.api.util.RiceKeyConstants;
25  import org.kuali.rice.core.web.format.Formatter;
26  import org.kuali.rice.kew.api.WorkflowDocument;
27  import org.kuali.rice.kim.api.identity.PersonService;
28  import org.kuali.rice.kim.api.role.RoleService;
29  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
30  import org.kuali.rice.krad.bo.BusinessObject;
31  import org.kuali.rice.krad.bo.GlobalBusinessObject;
32  import org.kuali.rice.krad.bo.PersistableBusinessObject;
33  import org.kuali.rice.krad.datadictionary.InactivationBlockingMetadata;
34  import org.kuali.rice.krad.datadictionary.validation.ErrorLevel;
35  import org.kuali.rice.krad.datadictionary.validation.result.ConstraintValidationResult;
36  import org.kuali.rice.krad.datadictionary.validation.result.DictionaryValidationResult;
37  import org.kuali.rice.krad.document.Document;
38  import org.kuali.rice.krad.maintenance.MaintenanceDocument;
39  import org.kuali.rice.krad.exception.ValidationException;
40  import org.kuali.rice.krad.maintenance.Maintainable;
41  import org.kuali.rice.krad.maintenance.MaintenanceDocumentAuthorizer;
42  import org.kuali.rice.krad.rules.rule.event.ApproveDocumentEvent;
43  import org.kuali.rice.krad.service.BusinessObjectService;
44  import org.kuali.rice.krad.service.DataDictionaryService;
45  import org.kuali.rice.krad.service.DataObjectAuthorizationService;
46  import org.kuali.rice.krad.service.DataObjectMetaDataService;
47  import org.kuali.rice.krad.service.DictionaryValidationService;
48  import org.kuali.rice.krad.service.InactivationBlockingDetectionService;
49  import org.kuali.rice.krad.service.KRADServiceLocator;
50  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
51  import org.kuali.rice.krad.service.PersistenceStructureService;
52  import org.kuali.rice.krad.util.ErrorMessage;
53  import org.kuali.rice.krad.util.ForeignKeyFieldsPopulationState;
54  import org.kuali.rice.krad.util.GlobalVariables;
55  import org.kuali.rice.krad.util.KRADConstants;
56  import org.kuali.rice.krad.util.KRADPropertyConstants;
57  import org.kuali.rice.krad.util.ObjectUtils;
58  import org.kuali.rice.krad.util.RouteToCompletionUtil;
59  import org.kuali.rice.krad.util.UrlFactory;
60  import org.kuali.rice.krad.workflow.service.WorkflowDocumentService;
61  import org.springframework.util.AutoPopulatingList;
62  
63  import java.security.GeneralSecurityException;
64  import java.util.ArrayList;
65  import java.util.Iterator;
66  import java.util.List;
67  import java.util.Map;
68  import java.util.Properties;
69  import java.util.Set;
70  
71  /**
72   * Contains all of the business rules that are common to all maintenance documents
73   *
74   * @author Kuali Rice Team (rice.collab@kuali.org)
75   */
76  public class MaintenanceDocumentRuleBase extends DocumentRuleBase implements MaintenanceDocumentRule {
77      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MaintenanceDocumentRuleBase.class);
78  
79      // these two constants are used to correctly prefix errors added to
80      // the global errors
81      public static final String MAINTAINABLE_ERROR_PREFIX = KRADConstants.MAINTENANCE_NEW_MAINTAINABLE;
82      public static final String DOCUMENT_ERROR_PREFIX = "document.";
83      public static final String MAINTAINABLE_ERROR_PATH = DOCUMENT_ERROR_PREFIX + "newMaintainableObject";
84  
85      private PersistenceStructureService persistenceStructureService;
86      private DataDictionaryService ddService;
87      private BusinessObjectService boService;
88      private DictionaryValidationService dictionaryValidationService;
89      private ConfigurationService configService;
90      private WorkflowDocumentService workflowDocumentService;
91      private PersonService personService;
92      private RoleService roleService;
93      private DataObjectMetaDataService dataObjectMetaDataService;
94      private DataObjectAuthorizationService dataObjectAuthorizationService;
95  
96      private Object oldDataObject;
97      private Object newDataObject;
98      private Class dataObjectClass;
99  
100     protected List priorErrorPath;
101 
102     /**
103      * Default constructor a MaintenanceDocumentRuleBase.java.
104      */
105     public MaintenanceDocumentRuleBase() {
106         priorErrorPath = new ArrayList();
107     }
108 
109     /**
110      * @see MaintenanceDocumentRule#processSaveDocument(org.kuali.rice.krad.document.Document)
111      */
112     @Override
113     public boolean processSaveDocument(Document document) {
114         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) document;
115 
116         // remove all items from the errorPath temporarily (because it may not
117         // be what we expect, or what we need)
118         clearErrorPath();
119 
120         // setup convenience pointers to the old & new bo
121         setupBaseConvenienceObjects(maintenanceDocument);
122 
123         // the document must be in a valid state for saving. this does not include business
124         // rules, but just enough testing that the document is populated and in a valid state
125         // to not cause exceptions when saved. if this passes, then the save will always occur,
126         // regardless of business rules.
127         if (!isDocumentValidForSave(maintenanceDocument)) {
128             resumeErrorPath();
129             return false;
130         }
131 
132         // apply rules that are specific to the class of the maintenance document
133         // (if implemented). this will always succeed if not overloaded by the
134         // subclass
135         if (!processCustomSaveDocumentBusinessRules(maintenanceDocument)) {
136             resumeErrorPath();
137             return false;
138         }
139 
140         // return the original set of items to the errorPath
141         resumeErrorPath();
142 
143         // return the original set of items to the errorPath, to ensure no impact
144         // on other upstream or downstream items that rely on the errorPath
145         return true;
146     }
147 
148     /**
149      * @see MaintenanceDocumentRule#processRouteDocument(org.kuali.rice.krad.document.Document)
150      */
151     @Override
152     public boolean processRouteDocument(Document document) {
153         LOG.info("processRouteDocument called");
154 
155         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) document;
156 
157         boolean completeRequestPending = RouteToCompletionUtil.checkIfAtleastOneAdHocCompleteRequestExist(
158                 maintenanceDocument);
159 
160         // Validate the document if the header is valid and no pending completion requests
161         if (completeRequestPending) {
162             return true;
163         }
164 
165         // get the documentAuthorizer for this document
166         MaintenanceDocumentAuthorizer documentAuthorizer =
167                 (MaintenanceDocumentAuthorizer) getDocumentDictionaryService().getDocumentAuthorizer(document);
168 
169         // remove all items from the errorPath temporarily (because it may not
170         // be what we expect, or what we need)
171         clearErrorPath();
172 
173         // setup convenience pointers to the old & new bo
174         setupBaseConvenienceObjects(maintenanceDocument);
175 
176         // apply rules that are common across all maintenance documents, regardless of class
177         processGlobalSaveDocumentBusinessRules(maintenanceDocument);
178 
179         // from here on, it is in a default-success mode, and will route unless one of the
180         // business rules stop it.
181         boolean success = true;
182 
183         WorkflowDocument workflowDocument = document.getDocumentHeader().getWorkflowDocument();
184         if (workflowDocument.isInitiated() || workflowDocument.isSaved()) {
185             try {
186                 success &= documentAuthorizer.canCreateOrMaintain((MaintenanceDocument) document,
187                         GlobalVariables.getUserSession().getPerson());
188                 if (success == false) {
189                     GlobalVariables.getMessageMap().putError(KRADConstants.DOCUMENT_ERRORS,
190                             RiceKeyConstants.AUTHORIZATION_ERROR_DOCUMENT,
191                             new String[]{GlobalVariables.getUserSession().getPerson().getPrincipalName(),
192                                     "Create/Maintain", getDocumentDictionaryService().getMaintenanceDocumentTypeName(
193                                     newDataObject.getClass())});
194                 }
195             } catch (RiceIllegalArgumentException e) {
196                 // TODO error message the right way
197                 GlobalVariables.getMessageMap().putError("Unable to determine authorization due to previous errors",
198                         "Unable to determine authorization due to previous errors");
199             }
200         }
201         // apply rules that are common across all maintenance documents, regardless of class
202         success &= processGlobalRouteDocumentBusinessRules(maintenanceDocument);
203 
204         // apply rules that are specific to the class of the maintenance document
205         // (if implemented). this will always succeed if not overloaded by the
206         // subclass
207         success &= processCustomRouteDocumentBusinessRules(maintenanceDocument);
208 
209         success &= processInactivationBlockChecking(maintenanceDocument);
210 
211         // return the original set of items to the errorPath, to ensure no impact
212         // on other upstream or downstream items that rely on the errorPath
213         resumeErrorPath();
214 
215         return success;
216     }
217 
218     /**
219      * Determines whether a document is inactivating the record being maintained
220      *
221      * @param maintenanceDocument
222      * @return true iff the document is inactivating the business object; false otherwise
223      */
224     protected boolean isDocumentInactivatingBusinessObject(MaintenanceDocument maintenanceDocument) {
225         if (maintenanceDocument.isEdit()) {
226             Class dataObjectClass = maintenanceDocument.getNewMaintainableObject().getDataObjectClass();
227             // we can only be inactivating a business object if we're editing it
228             if (dataObjectClass != null && MutableInactivatable.class.isAssignableFrom(dataObjectClass)) {
229                 MutableInactivatable oldInactivateableBO = (MutableInactivatable) oldDataObject;
230                 MutableInactivatable newInactivateableBO = (MutableInactivatable) newDataObject;
231 
232                 return oldInactivateableBO.isActive() && !newInactivateableBO.isActive();
233             }
234         }
235         return false;
236     }
237 
238     /**
239      * Determines whether this document has been inactivation blocked
240      *
241      * @param maintenanceDocument
242      * @return true iff there is NOTHING that blocks this record
243      */
244     protected boolean processInactivationBlockChecking(MaintenanceDocument maintenanceDocument) {
245         if (isDocumentInactivatingBusinessObject(maintenanceDocument)) {
246             Class dataObjectClass = maintenanceDocument.getNewMaintainableObject().getDataObjectClass();
247             Set<InactivationBlockingMetadata> inactivationBlockingMetadatas =
248                     getDataDictionaryService().getAllInactivationBlockingDefinitions(dataObjectClass);
249 
250             if (inactivationBlockingMetadatas != null) {
251                 for (InactivationBlockingMetadata inactivationBlockingMetadata : inactivationBlockingMetadatas) {
252                     // for the purposes of maint doc validation, we only need to look for the first blocking record
253 
254                     // we found a blocking record, so we return false
255                     if (!processInactivationBlockChecking(maintenanceDocument, inactivationBlockingMetadata)) {
256                         return false;
257                     }
258                 }
259             }
260         }
261         return true;
262     }
263 
264     /**
265      * Given a InactivationBlockingMetadata, which represents a relationship that may block inactivation of a BO, it
266      * determines whether there
267      * is a record that violates the blocking definition
268      *
269      * @param maintenanceDocument
270      * @param inactivationBlockingMetadata
271      * @return true iff, based on the InactivationBlockingMetadata, the maintenance document should be allowed to route
272      */
273     protected boolean processInactivationBlockChecking(MaintenanceDocument maintenanceDocument,
274             InactivationBlockingMetadata inactivationBlockingMetadata) {
275         if (newDataObject instanceof PersistableBusinessObject) {
276             String inactivationBlockingDetectionServiceBeanName =
277                     inactivationBlockingMetadata.getInactivationBlockingDetectionServiceBeanName();
278             if (StringUtils.isBlank(inactivationBlockingDetectionServiceBeanName)) {
279                 inactivationBlockingDetectionServiceBeanName =
280                         KRADServiceLocatorWeb.DEFAULT_INACTIVATION_BLOCKING_DETECTION_SERVICE;
281             }
282             InactivationBlockingDetectionService inactivationBlockingDetectionService =
283                     KRADServiceLocatorWeb.getInactivationBlockingDetectionService(
284                             inactivationBlockingDetectionServiceBeanName);
285 
286             boolean foundBlockingRecord = inactivationBlockingDetectionService.hasABlockingRecord(
287                     (PersistableBusinessObject) newDataObject, inactivationBlockingMetadata);
288 
289             if (foundBlockingRecord) {
290                 putInactivationBlockingErrorOnPage(maintenanceDocument, inactivationBlockingMetadata);
291             }
292 
293             return !foundBlockingRecord;
294         }
295 
296         return true;
297     }
298 
299     /**
300      * If there is a violation of an InactivationBlockingMetadata, it prints out an appropriate error into the error
301      * map
302      *
303      * @param document
304      * @param inactivationBlockingMetadata
305      */
306     protected void putInactivationBlockingErrorOnPage(MaintenanceDocument document,
307             InactivationBlockingMetadata inactivationBlockingMetadata) {
308         if (!getPersistenceStructureService().hasPrimaryKeyFieldValues(newDataObject)) {
309             throw new RuntimeException("Maintenance document did not have all primary key values filled in.");
310         }
311         Properties parameters = new Properties();
312         parameters.put(KRADConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE,
313                 inactivationBlockingMetadata.getBlockedBusinessObjectClass().getName());
314         parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER,
315                 KRADConstants.METHOD_DISPLAY_ALL_INACTIVATION_BLOCKERS);
316 
317         List keys = new ArrayList();
318         if (getPersistenceStructureService().isPersistable(newDataObject.getClass())) {
319             keys = getPersistenceStructureService().listPrimaryKeyFieldNames(newDataObject.getClass());
320         }
321 
322         // build key value url parameters used to retrieve the business object
323         String keyName = null;
324         for (Iterator iter = keys.iterator(); iter.hasNext(); ) {
325             keyName = (String) iter.next();
326 
327             Object keyValue = null;
328             if (keyName != null) {
329                 keyValue = ObjectUtils.getPropertyValue(newDataObject, keyName);
330             }
331 
332             if (keyValue == null) {
333                 keyValue = "";
334             } else if (keyValue instanceof java.sql.Date) { //format the date for passing in url
335                 if (Formatter.findFormatter(keyValue.getClass()) != null) {
336                     Formatter formatter = Formatter.getFormatter(keyValue.getClass());
337                     keyValue = (String) formatter.format(keyValue);
338                 }
339             } else {
340                 keyValue = keyValue.toString();
341             }
342 
343             // Encrypt value if it is a secure field
344             if (getDataObjectAuthorizationService().attributeValueNeedsToBeEncryptedOnFormsAndLinks(
345                     inactivationBlockingMetadata.getBlockedBusinessObjectClass(), keyName)) {
346                 try {
347                     keyValue = CoreApiServiceLocator.getEncryptionService().encrypt(keyValue);
348                 } catch (GeneralSecurityException e) {
349                     LOG.error("Exception while trying to encrypted value for inquiry framework.", e);
350                     throw new RuntimeException(e);
351                 }
352             }
353 
354             parameters.put(keyName, keyValue);
355         }
356 
357         String blockingUrl = UrlFactory.parameterizeUrl(KRADConstants.DISPLAY_ALL_INACTIVATION_BLOCKERS_ACTION,
358                 parameters);
359 
360         // post an error about the locked document
361         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,
362                 RiceKeyConstants.ERROR_INACTIVATION_BLOCKED, blockingUrl);
363     }
364 
365     /**
366      * @see MaintenanceDocumentRule#processApproveDocument(org.kuali.rice.krad.rules.rule.event.ApproveDocumentEvent)
367      */
368     @Override
369     public boolean processApproveDocument(ApproveDocumentEvent approveEvent) {
370         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) approveEvent.getDocument();
371 
372         // remove all items from the errorPath temporarily (because it may not
373         // be what we expect, or what we need)
374         clearErrorPath();
375 
376         // setup convenience pointers to the old & new bo
377         setupBaseConvenienceObjects(maintenanceDocument);
378 
379         // apply rules that are common across all maintenance documents, regardless of class
380         processGlobalSaveDocumentBusinessRules(maintenanceDocument);
381 
382         // from here on, it is in a default-success mode, and will approve unless one of the
383         // business rules stop it.
384         boolean success = true;
385 
386         // apply rules that are common across all maintenance documents, regardless of class
387         success &= processGlobalApproveDocumentBusinessRules(maintenanceDocument);
388 
389         // apply rules that are specific to the class of the maintenance document
390         // (if implemented). this will always succeed if not overloaded by the
391         // subclass
392         success &= processCustomApproveDocumentBusinessRules(maintenanceDocument);
393 
394         // return the original set of items to the errorPath, to ensure no impact
395         // on other upstream or downstream items that rely on the errorPath
396         resumeErrorPath();
397 
398         return success;
399     }
400 
401     /**
402      * This method is a convenience method to easily add a Document level error (ie, one not tied to a specific field,
403      * but
404      * applicable to the whole document).
405      *
406      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
407      */
408     protected void putGlobalError(String errorConstant) {
409         if (!errorAlreadyExists(KRADConstants.DOCUMENT_ERRORS, errorConstant)) {
410             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.DOCUMENT_ERRORS, errorConstant);
411         }
412     }
413 
414     /**
415      * This method is a convenience method to easily add a Document level error (ie, one not tied to a specific field,
416      * but
417      * applicable to the whole document).
418      *
419      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
420      * @param parameter - Replacement value for part of the error message.
421      */
422     protected void putGlobalError(String errorConstant, String parameter) {
423         if (!errorAlreadyExists(KRADConstants.DOCUMENT_ERRORS, errorConstant)) {
424             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.DOCUMENT_ERRORS, errorConstant,
425                     parameter);
426         }
427     }
428 
429     /**
430      * This method is a convenience method to easily add a Document level error (ie, one not tied to a specific field,
431      * but
432      * applicable to the whole document).
433      *
434      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
435      * @param parameters - Array of replacement values for part of the error message.
436      */
437     protected void putGlobalError(String errorConstant, String[] parameters) {
438         if (!errorAlreadyExists(KRADConstants.DOCUMENT_ERRORS, errorConstant)) {
439             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.DOCUMENT_ERRORS, errorConstant,
440                     parameters);
441         }
442     }
443 
444     /**
445      * This method is a convenience method to add a property-specific error to the global errors list. This method
446      * makes
447      * sure that
448      * the correct prefix is added to the property name so that it will display correctly on maintenance documents.
449      *
450      * @param propertyName - Property name of the element that is associated with the error. Used to mark the field as
451      * errored in
452      * the UI.
453      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
454      */
455     protected void putFieldError(String propertyName, String errorConstant) {
456         if (!errorAlreadyExists(MAINTAINABLE_ERROR_PREFIX + propertyName, errorConstant)) {
457             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(MAINTAINABLE_ERROR_PREFIX + propertyName,
458                     errorConstant);
459         }
460     }
461 
462     /**
463      * This method is a convenience method to add a property-specific error to the global errors list. This method
464      * makes
465      * sure that
466      * the correct prefix is added to the property name so that it will display correctly on maintenance documents.
467      *
468      * @param propertyName - Property name of the element that is associated with the error. Used to mark the field as
469      * errored in
470      * the UI.
471      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
472      * @param parameter - Single parameter value that can be used in the message so that you can display specific
473      * values
474      * to the
475      * user.
476      */
477     protected void putFieldError(String propertyName, String errorConstant, String parameter) {
478         if (!errorAlreadyExists(MAINTAINABLE_ERROR_PREFIX + propertyName, errorConstant)) {
479             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(MAINTAINABLE_ERROR_PREFIX + propertyName,
480                     errorConstant, parameter);
481         }
482     }
483 
484     /**
485      * This method is a convenience method to add a property-specific error to the global errors list. This method
486      * makes
487      * sure that
488      * the correct prefix is added to the property name so that it will display correctly on maintenance documents.
489      *
490      * @param propertyName - Property name of the element that is associated with the error. Used to mark the field as
491      * errored in
492      * the UI.
493      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
494      * @param parameters - Array of strings holding values that can be used in the message so that you can display
495      * specific values
496      * to the user.
497      */
498     protected void putFieldError(String propertyName, String errorConstant, String[] parameters) {
499         if (!errorAlreadyExists(MAINTAINABLE_ERROR_PREFIX + propertyName, errorConstant)) {
500             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(MAINTAINABLE_ERROR_PREFIX + propertyName,
501                     errorConstant, parameters);
502         }
503     }
504 
505     /**
506      * Adds a property-specific error to the global errors list, with the DD short label as the single argument.
507      *
508      * @param propertyName - Property name of the element that is associated with the error. Used to mark the field as
509      * errored in
510      * the UI.
511      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
512      */
513     protected void putFieldErrorWithShortLabel(String propertyName, String errorConstant) {
514         String shortLabel = getDataDictionaryService().getAttributeShortLabel(dataObjectClass, propertyName);
515         putFieldError(propertyName, errorConstant, shortLabel);
516     }
517 
518     /**
519      * This method is a convenience method to add a property-specific document error to the global errors list. This
520      * method makes
521      * sure that the correct prefix is added to the property name so that it will display correctly on maintenance
522      * documents.
523      *
524      * @param propertyName - Property name of the element that is associated with the error. Used to mark the field as
525      * errored in
526      * the UI.
527      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
528      * @param parameter - Single parameter value that can be used in the message so that you can display specific
529      * values
530      * to the
531      * user.
532      */
533     protected void putDocumentError(String propertyName, String errorConstant, String parameter) {
534         if (!errorAlreadyExists(DOCUMENT_ERROR_PREFIX + propertyName, errorConstant)) {
535             GlobalVariables.getMessageMap().putError(DOCUMENT_ERROR_PREFIX + propertyName, errorConstant, parameter);
536         }
537     }
538 
539     /**
540      * This method is a convenience method to add a property-specific document error to the global errors list. This
541      * method makes
542      * sure that the correct prefix is added to the property name so that it will display correctly on maintenance
543      * documents.
544      *
545      * @param propertyName - Property name of the element that is associated with the error. Used to mark the field as
546      * errored in
547      * the UI.
548      * @param errorConstant - Error Constant that can be mapped to a resource for the actual text message.
549      * @param parameters - Array of String parameters that can be used in the message so that you can display specific
550      * values to the
551      * user.
552      */
553     protected void putDocumentError(String propertyName, String errorConstant, String[] parameters) {
554         GlobalVariables.getMessageMap().putError(DOCUMENT_ERROR_PREFIX + propertyName, errorConstant, parameters);
555     }
556 
557     /**
558      * Convenience method to determine whether the field already has the message indicated.
559      *
560      * This is useful if you want to suppress duplicate error messages on the same field.
561      *
562      * @param propertyName - propertyName you want to test on
563      * @param errorConstant - errorConstant you want to test
564      * @return returns True if the propertyName indicated already has the errorConstant indicated, false otherwise
565      */
566     protected boolean errorAlreadyExists(String propertyName, String errorConstant) {
567         if (GlobalVariables.getMessageMap().fieldHasMessage(propertyName, errorConstant)) {
568             return true;
569         } else {
570             return false;
571         }
572     }
573 
574     /**
575      * This method specifically doesn't put any prefixes before the error so that the developer can do things specific
576      * to the
577      * globals errors (like newDelegateChangeDocument errors)
578      *
579      * @param propertyName
580      * @param errorConstant
581      */
582     protected void putGlobalsError(String propertyName, String errorConstant) {
583         if (!errorAlreadyExists(propertyName, errorConstant)) {
584             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(propertyName, errorConstant);
585         }
586     }
587 
588     /**
589      * This method specifically doesn't put any prefixes before the error so that the developer can do things specific
590      * to the
591      * globals errors (like newDelegateChangeDocument errors)
592      *
593      * @param propertyName
594      * @param errorConstant
595      * @param parameter
596      */
597     protected void putGlobalsError(String propertyName, String errorConstant, String parameter) {
598         if (!errorAlreadyExists(propertyName, errorConstant)) {
599             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(propertyName, errorConstant, parameter);
600         }
601     }
602 
603     /**
604      * This method is used to deal with error paths that are not what we expect them to be. This method, along with
605      * resumeErrorPath() are used to temporarily clear the errorPath, and then return it to the original state after
606      * the
607      * rule is
608      * executed.
609      *
610      * This method is called at the very beginning of rule enforcement and pulls a copy of the contents of the
611      * errorPath
612      * ArrayList
613      * to a local arrayList for temporary storage.
614      */
615     protected void clearErrorPath() {
616         // add all the items from the global list to the local list
617         priorErrorPath.addAll(GlobalVariables.getMessageMap().getErrorPath());
618 
619         // clear the global list
620         GlobalVariables.getMessageMap().getErrorPath().clear();
621     }
622 
623     /**
624      * This method is used to deal with error paths that are not what we expect them to be. This method, along with
625      * clearErrorPath()
626      * are used to temporarily clear the errorPath, and then return it to the original state after the rule is
627      * executed.
628      *
629      * This method is called at the very end of the rule enforcement, and returns the temporarily stored copy of the
630      * errorPath to
631      * the global errorPath, so that no other classes are interrupted.
632      */
633     protected void resumeErrorPath() {
634         // revert the global errorPath back to what it was when we entered this
635         // class
636         GlobalVariables.getMessageMap().getErrorPath().addAll(priorErrorPath);
637     }
638 
639     /**
640      * Executes the DataDictionary Validation against the document.
641      *
642      * @param document
643      * @return true if it passes DD validation, false otherwise
644      */
645     protected boolean dataDictionaryValidate(MaintenanceDocument document) {
646         // default to success if no failures
647         boolean success = true;
648         LOG.debug("MaintenanceDocument validation beginning");
649 
650         // explicitly put the errorPath that the dictionaryValidationService
651         // requires
652         GlobalVariables.getMessageMap().addToErrorPath("document.newMaintainableObject");
653 
654         // document must have a newMaintainable object
655         Maintainable newMaintainable = document.getNewMaintainableObject();
656         if (newMaintainable == null) {
657             GlobalVariables.getMessageMap().removeFromErrorPath("document.newMaintainableObject");
658             throw new ValidationException(
659                     "Maintainable object from Maintenance Document '" + document.getDocumentTitle() +
660                             "' is null, unable to proceed.");
661         }
662 
663         // document's newMaintainable must contain an object (ie, not null)
664         Object dataObject = newMaintainable.getDataObject();
665         if (dataObject == null) {
666             GlobalVariables.getMessageMap().removeFromErrorPath("document.newMaintainableObject.");
667             throw new ValidationException("Maintainable's component business object is null.");
668         }
669 
670         // check if there are errors in validating the business object
671         GlobalVariables.getMessageMap().addToErrorPath("dataObject");
672         DictionaryValidationResult dictionaryValidationResult = getDictionaryValidationService().validate(
673                 newDataObject);
674         if (dictionaryValidationResult.getNumberOfErrors() > 0) {
675             success &= false;
676 
677             for (ConstraintValidationResult cvr : dictionaryValidationResult) {
678                 if (cvr.getStatus() == ErrorLevel.ERROR) {
679                     GlobalVariables.getMessageMap().putError(cvr.getAttributePath(), cvr.getErrorKey());
680                 }
681             }
682         }
683 
684         // validate default existence checks
685         // TODO: Default existence checks need support for general data objects, see KULRICE-7666
686         //        success &= getDictionaryValidationService().validateDefaultExistenceChecks((BusinessObject) dataObject);
687         //        GlobalVariables.getMessageMap().removeFromErrorPath("dataObject");
688 
689         // explicitly remove the errorPath we've added
690         GlobalVariables.getMessageMap().removeFromErrorPath("document.newMaintainableObject");
691 
692         LOG.debug("MaintenanceDocument validation ending");
693         return true;
694     }
695 
696     /**
697      * This method checks the two major cases that may violate primary key integrity.
698      *
699      * 1. Disallow changing of the primary keys on an EDIT maintenance document. Other fields can be changed, but once
700      * the primary
701      * keys have been set, they are permanent.
702      *
703      * 2. Disallow creating a new object whose primary key values are already present in the system on a CREATE NEW
704      * maintenance
705      * document.
706      *
707      * This method also will add new Errors to the Global Error Map.
708      *
709      * @param document - The Maintenance Document being tested.
710      * @return Returns false if either test failed, otherwise returns true.
711      */
712     protected boolean primaryKeyCheck(MaintenanceDocument document) {
713         // default to success if no failures
714         boolean success = true;
715         Class<?> dataObjectClass = document.getNewMaintainableObject().getDataObjectClass();
716 
717         Object oldBo = document.getOldMaintainableObject().getDataObject();
718         Object newDataObject = document.getNewMaintainableObject().getDataObject();
719 
720         // We dont do primaryKeyChecks on Global Business Object maintenance documents. This is
721         // because it doesnt really make any sense to do so, given the behavior of Globals. When a
722         // Global Document completes, it will update or create a new record for each BO in the list.
723         // As a result, there's no problem with having existing BO records in the system, they will
724         // simply get updated.
725         if (newDataObject instanceof GlobalBusinessObject) {
726             return success;
727         }
728 
729         // fail and complain if the person has changed the primary keys on
730         // an EDIT maintenance document.
731         if (document.isEdit()) {
732             if (!getDataObjectMetaDataService().equalsByPrimaryKeys(oldBo, newDataObject)) {
733                 // add a complaint to the errors
734                 putDocumentError(KRADConstants.DOCUMENT_ERRORS,
735                         RiceKeyConstants.ERROR_DOCUMENT_MAINTENANCE_PRIMARY_KEYS_CHANGED_ON_EDIT,
736                         getHumanReadablePrimaryKeyFieldNames(dataObjectClass));
737                 success &= false;
738             }
739         }
740 
741         // fail and complain if the person has selected a new object with keys that already exist
742         // in the DB.
743         else if (document.isNew()) {
744 
745             // TODO: when/if we have standard support for DO retrieval, do this check for DO's
746             if (newDataObject instanceof PersistableBusinessObject) {
747 
748                 // get a map of the pk field names and values
749                 Map<String, ?> newPkFields = getDataObjectMetaDataService().getPrimaryKeyFieldValues(newDataObject);
750 
751                 // TODO: Good suggestion from Aaron, dont bother checking the DB, if all of the
752                 // objects PK fields dont have values. If any are null or empty, then
753                 // we're done. The current way wont fail, but it will make a wasteful
754                 // DB call that may not be necessary, and we want to minimize these.
755 
756                 // attempt to do a lookup, see if this object already exists by these Primary Keys
757                 PersistableBusinessObject testBo = getBoService().findByPrimaryKey(dataObjectClass.asSubclass(
758                         PersistableBusinessObject.class), newPkFields);
759 
760                 // if the retrieve was successful, then this object already exists, and we need
761                 // to complain
762                 if (testBo != null) {
763                     putDocumentError(KRADConstants.DOCUMENT_ERRORS,
764                             RiceKeyConstants.ERROR_DOCUMENT_MAINTENANCE_KEYS_ALREADY_EXIST_ON_CREATE_NEW,
765                             getHumanReadablePrimaryKeyFieldNames(dataObjectClass));
766                     success &= false;
767                 }
768             }
769         }
770 
771         return success;
772     }
773 
774     /**
775      * This method creates a human-readable string of the class' primary key field names, as designated by the
776      * DataDictionary.
777      *
778      * @param dataObjectClass
779      * @return
780      */
781     protected String getHumanReadablePrimaryKeyFieldNames(Class<?> dataObjectClass) {
782         String delim = "";
783         StringBuffer pkFieldNames = new StringBuffer();
784 
785         // get a list of all the primary key field names, walk through them
786         List<String> pkFields = getDataObjectMetaDataService().listPrimaryKeyFieldNames(dataObjectClass);
787         for (Iterator<String> iter = pkFields.iterator(); iter.hasNext(); ) {
788             String pkFieldName = (String) iter.next();
789 
790             // TODO should this be getting labels from the view dictionary
791             // use the DataDictionary service to translate field name into human-readable label
792             String humanReadableFieldName = getDataDictionaryService().getAttributeLabel(dataObjectClass, pkFieldName);
793 
794             // append the next field
795             pkFieldNames.append(delim + humanReadableFieldName);
796 
797             // separate names with commas after the first one
798             if (delim.equalsIgnoreCase("")) {
799                 delim = ", ";
800             }
801         }
802 
803         return pkFieldNames.toString();
804     }
805 
806     /**
807      * This method enforces all business rules that are common to all maintenance documents which must be tested before
808      * doing an
809      * approval.
810      *
811      * It can be overloaded in special cases where a MaintenanceDocument has very special needs that would be contrary
812      * to what is
813      * enforced here.
814      *
815      * @param document - a populated MaintenanceDocument instance
816      * @return true if the document can be approved, false if not
817      */
818     protected boolean processGlobalApproveDocumentBusinessRules(MaintenanceDocument document) {
819         return true;
820     }
821 
822     /**
823      * This method enforces all business rules that are common to all maintenance documents which must be tested before
824      * doing a
825      * route.
826      *
827      * It can be overloaded in special cases where a MaintenanceDocument has very special needs that would be contrary
828      * to what is
829      * enforced here.
830      *
831      * @param document - a populated MaintenanceDocument instance
832      * @return true if the document can be routed, false if not
833      */
834     protected boolean processGlobalRouteDocumentBusinessRules(MaintenanceDocument document) {
835         boolean success = true;
836 
837         // require a document description field
838         success &= checkEmptyDocumentField(
839                 KRADPropertyConstants.DOCUMENT_HEADER + "." + KRADPropertyConstants.DOCUMENT_DESCRIPTION,
840                 document.getDocumentHeader().getDocumentDescription(), "Description");
841 
842         return success;
843     }
844 
845     /**
846      * This method enforces all business rules that are common to all maintenance documents which must be tested before
847      * doing a
848      * save.
849      *
850      * It can be overloaded in special cases where a MaintenanceDocument has very special needs that would be contrary
851      * to what is
852      * enforced here.
853      *
854      * Note that although this method returns a true or false to indicate whether the save should happen or not, this
855      * result may not
856      * be followed by the calling method. In other words, the boolean result will likely be ignored, and the document
857      * saved,
858      * regardless.
859      *
860      * @param document - a populated MaintenanceDocument instance
861      * @return true if all business rules succeed, false if not
862      */
863     protected boolean processGlobalSaveDocumentBusinessRules(MaintenanceDocument document) {
864         // default to success
865         boolean success = true;
866 
867         // do generic checks that impact primary key violations
868         success &= primaryKeyCheck(document);
869 
870         // this is happening only on the processSave, since a Save happens in both the
871         // Route and Save events.
872         success &= this.dataDictionaryValidate(document);
873 
874         return success;
875     }
876 
877     /**
878      * This method should be overridden to provide custom rules for processing document saving
879      *
880      * @param document
881      * @return boolean
882      */
883     protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) {
884         return true;
885     }
886 
887     /**
888      * This method should be overridden to provide custom rules for processing document routing
889      *
890      * @param document
891      * @return boolean
892      */
893     protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) {
894         return true;
895     }
896 
897     /**
898      * This method should be overridden to provide custom rules for processing document approval.
899      *
900      * @param document
901      * @return booelan
902      */
903     protected boolean processCustomApproveDocumentBusinessRules(MaintenanceDocument document) {
904         return true;
905     }
906 
907     // Document Validation Helper Methods
908 
909     /**
910      * This method checks to see if the document is in a state that it can be saved without causing exceptions.
911      *
912      * Note that Business Rules are NOT enforced here, only validity checks.
913      *
914      * This method will only return false if the document is in such a state that routing it will cause
915      * RunTimeExceptions.
916      *
917      * @param maintenanceDocument - a populated MaintenaceDocument instance.
918      * @return boolean - returns true unless the object is in an invalid state.
919      */
920     protected boolean isDocumentValidForSave(MaintenanceDocument maintenanceDocument) {
921 
922         boolean success = true;
923 
924         success &= super.isDocumentOverviewValid(maintenanceDocument);
925         success &= validateDocumentStructure((Document) maintenanceDocument);
926         success &= validateMaintenanceDocument(maintenanceDocument);
927         success &= validateGlobalBusinessObjectPersistable(maintenanceDocument);
928         return success;
929     }
930 
931     /**
932      * This method makes sure the document itself is valid, and has the necessary fields populated to be routable.
933      *
934      * This is not a business rules test, rather its a structure test to make sure that the document will not cause
935      * exceptions
936      * before routing.
937      *
938      * @param document - document to be tested
939      * @return false if the document is missing key values, true otherwise
940      */
941     protected boolean validateDocumentStructure(Document document) {
942         boolean success = true;
943 
944         // document must have a populated documentNumber
945         String documentHeaderId = document.getDocumentNumber();
946         if (documentHeaderId == null || StringUtils.isEmpty(documentHeaderId)) {
947             throw new ValidationException("Document has no document number, unable to proceed.");
948         }
949 
950         return success;
951     }
952 
953     /**
954      * This method checks to make sure the document is a valid maintenanceDocument, and has the necessary values
955      * populated such that
956      * it will not cause exceptions in later routing or business rules testing.
957      *
958      * This is not a business rules test.
959      *
960      * @param maintenanceDocument - document to be tested
961      * @return whether maintenance doc passes
962      * @throws ValidationException
963      */
964     protected boolean validateMaintenanceDocument(MaintenanceDocument maintenanceDocument) {
965         boolean success = true;
966         Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
967 
968         // document must have a newMaintainable object
969         if (newMaintainable == null) {
970             throw new ValidationException(
971                     "Maintainable object from Maintenance Document '" + maintenanceDocument.getDocumentTitle() +
972                             "' is null, unable to proceed.");
973         }
974 
975         // document's newMaintainable must contain an object (ie, not null)
976         if (newMaintainable.getDataObject() == null) {
977             throw new ValidationException("Maintainable's component data object is null.");
978         }
979 
980         return success;
981     }
982 
983     /**
984      * This method checks whether this maint doc contains Global Business Objects, and if so, whether the GBOs are in a
985      * persistable
986      * state. This will return false if this method determines that the GBO will cause a SQL Exception when the
987      * document
988      * is
989      * persisted.
990      *
991      * @param document
992      * @return False when the method determines that the contained Global Business Object will cause a SQL Exception,
993      *         and the
994      *         document should not be saved. It will return True otherwise.
995      */
996     protected boolean validateGlobalBusinessObjectPersistable(MaintenanceDocument document) {
997         boolean success = true;
998 
999         if (document.getNewMaintainableObject() == null) {
1000             return success;
1001         }
1002         if (document.getNewMaintainableObject().getDataObject() == null) {
1003             return success;
1004         }
1005         if (!(document.getNewMaintainableObject().getDataObject() instanceof GlobalBusinessObject)) {
1006             return success;
1007         }
1008 
1009         PersistableBusinessObject bo = (PersistableBusinessObject) document.getNewMaintainableObject().getDataObject();
1010         GlobalBusinessObject gbo = (GlobalBusinessObject) bo;
1011         return gbo.isPersistable();
1012     }
1013 
1014     /**
1015      * This method tests to make sure the MaintenanceDocument passed in is based on the class you are expecting.
1016      *
1017      * It does this based on the NewMaintainableObject of the MaintenanceDocument.
1018      *
1019      * @param document - MaintenanceDocument instance you want to test
1020      * @param clazz - class you are expecting the MaintenanceDocument to be based on
1021      * @return true if they match, false if not
1022      */
1023     protected boolean isCorrectMaintenanceClass(MaintenanceDocument document, Class clazz) {
1024         // disallow null arguments
1025         if (document == null || clazz == null) {
1026             throw new IllegalArgumentException("Null arguments were passed in.");
1027         }
1028 
1029         // compare the class names
1030         if (clazz.toString().equals(document.getNewMaintainableObject().getDataObjectClass().toString())) {
1031             return true;
1032         } else {
1033             return false;
1034         }
1035     }
1036 
1037     /**
1038      * This method accepts an object, and attempts to determine whether it is empty by this method's definition.
1039      *
1040      * OBJECT RESULT null false empty-string false whitespace false otherwise true
1041      *
1042      * If the result is false, it will add an object field error to the Global Errors.
1043      *
1044      * @param valueToTest - any object to test, usually a String
1045      * @param propertyName - the name of the property being tested
1046      * @return true or false, by the description above
1047      */
1048     protected boolean checkEmptyBOField(String propertyName, Object valueToTest, String parameter) {
1049         boolean success = true;
1050 
1051         success = checkEmptyValue(valueToTest);
1052 
1053         // if failed, then add a field error
1054         if (!success) {
1055             putFieldError(propertyName, RiceKeyConstants.ERROR_REQUIRED, parameter);
1056         }
1057 
1058         return success;
1059     }
1060 
1061     /**
1062      * This method accepts document field (such as , and attempts to determine whether it is empty by this method's
1063      * definition.
1064      *
1065      * OBJECT RESULT null false empty-string false whitespace false otherwise true
1066      *
1067      * If the result is false, it will add document field error to the Global Errors.
1068      *
1069      * @param valueToTest - any object to test, usually a String
1070      * @param propertyName - the name of the property being tested
1071      * @return true or false, by the description above
1072      */
1073     protected boolean checkEmptyDocumentField(String propertyName, Object valueToTest, String parameter) {
1074         boolean success = true;
1075         success = checkEmptyValue(valueToTest);
1076         if (!success) {
1077             putDocumentError(propertyName, RiceKeyConstants.ERROR_REQUIRED, parameter);
1078         }
1079         return success;
1080     }
1081 
1082     /**
1083      * This method accepts document field (such as , and attempts to determine whether it is empty by this method's
1084      * definition.
1085      *
1086      * OBJECT RESULT null false empty-string false whitespace false otherwise true
1087      *
1088      * It will the result as a boolean
1089      *
1090      * @param valueToTest - any object to test, usually a String
1091      */
1092     protected boolean checkEmptyValue(Object valueToTest) {
1093         boolean success = true;
1094 
1095         // if its not a string, only fail if its a null object
1096         if (valueToTest == null) {
1097             success = false;
1098         } else {
1099             // test for null, empty-string, or whitespace if its a string
1100             if (valueToTest instanceof String) {
1101                 if (StringUtils.isBlank((String) valueToTest)) {
1102                     success = false;
1103                 }
1104             }
1105         }
1106 
1107         return success;
1108     }
1109 
1110     /**
1111      * This method is used during debugging to dump the contents of the error map, including the key names. It is not
1112      * used by the
1113      * application in normal circumstances at all.
1114      */
1115     protected void showErrorMap() {
1116         if (GlobalVariables.getMessageMap().hasNoErrors()) {
1117             return;
1118         }
1119 
1120         for (Iterator i = GlobalVariables.getMessageMap().getAllPropertiesAndErrors().iterator(); i.hasNext(); ) {
1121             Map.Entry e = (Map.Entry) i.next();
1122 
1123             AutoPopulatingList errorList = (AutoPopulatingList) e.getValue();
1124             for (Iterator j = errorList.iterator(); j.hasNext(); ) {
1125                 ErrorMessage em = (ErrorMessage) j.next();
1126 
1127                 if (em.getMessageParameters() == null) {
1128                     LOG.error(e.getKey().toString() + " = " + em.getErrorKey());
1129                 } else {
1130                     LOG.error(e.getKey().toString() + " = " + em.getErrorKey() + " : " +
1131                             em.getMessageParameters().toString());
1132                 }
1133             }
1134         }
1135     }
1136 
1137     /**
1138      * @see MaintenanceDocumentRule#setupBaseConvenienceObjects(org.kuali.rice.krad.maintenance.MaintenanceDocument)
1139      */
1140     public void setupBaseConvenienceObjects(MaintenanceDocument document) {
1141         // setup oldAccount convenience objects, make sure all possible sub-objects are populated
1142         oldDataObject = document.getOldMaintainableObject().getDataObject();
1143         if (oldDataObject != null && oldDataObject instanceof PersistableBusinessObject) {
1144             ((PersistableBusinessObject) oldDataObject).refreshNonUpdateableReferences();
1145         }
1146 
1147         // setup newAccount convenience objects, make sure all possible sub-objects are populated
1148         newDataObject = document.getNewMaintainableObject().getDataObject();
1149         if (newDataObject instanceof PersistableBusinessObject) {
1150             ((PersistableBusinessObject) newDataObject).refreshNonUpdateableReferences();
1151         }
1152 
1153         dataObjectClass = document.getNewMaintainableObject().getDataObjectClass();
1154 
1155         // call the setupConvenienceObjects in the subclass, if a subclass exists
1156         setupConvenienceObjects();
1157     }
1158 
1159     public void setupConvenienceObjects() {
1160         // should always be overriden by subclass
1161     }
1162 
1163     /**
1164      * This method checks to make sure that if the foreign-key fields for the given reference attributes have any
1165      * fields filled out,that all fields are filled out.
1166      *
1167      * If any are filled out, but all are not, it will return false and add a global error message about the problem.
1168      *
1169      * @param referenceName - The name of the reference object, whose foreign-key fields must be all-or-none filled
1170      * out.
1171      * @return true if this is the case, false if not
1172      */
1173     protected boolean checkForPartiallyFilledOutReferenceForeignKeys(String referenceName) {
1174         boolean success = true;
1175 
1176         if (newDataObject instanceof PersistableBusinessObject) {
1177             ForeignKeyFieldsPopulationState fkFieldsState;
1178             fkFieldsState = getPersistenceStructureService().getForeignKeyFieldsPopulationState(
1179                     (PersistableBusinessObject) newDataObject, referenceName);
1180 
1181             // determine result
1182             if (fkFieldsState.isAnyFieldsPopulated() && !fkFieldsState.isAllFieldsPopulated()) {
1183                 success = false;
1184 
1185                 // add errors if appropriate
1186 
1187                 // get the full set of foreign-keys
1188                 List fKeys = new ArrayList(getPersistenceStructureService().getForeignKeysForReference(
1189                         newDataObject.getClass().asSubclass(PersistableBusinessObject.class), referenceName).keySet());
1190                 String fKeysReadable = consolidateFieldNames(fKeys, ", ").toString();
1191 
1192                 // walk through the missing fields
1193                 for (Iterator iter = fkFieldsState.getUnpopulatedFieldNames().iterator(); iter.hasNext(); ) {
1194                     String fieldName = (String) iter.next();
1195 
1196                     // get the human-readable name
1197                     String fieldNameReadable = getDataDictionaryService().getAttributeLabel(newDataObject.getClass(),
1198                             fieldName);
1199 
1200                     // add a field error
1201                     putFieldError(fieldName, RiceKeyConstants.ERROR_DOCUMENT_MAINTENANCE_PARTIALLY_FILLED_OUT_REF_FKEYS,
1202                             new String[]{fieldNameReadable, fKeysReadable});
1203                 }
1204             }
1205         }
1206 
1207         return success;
1208     }
1209 
1210     /**
1211      * This method turns a list of field property names, into a delimited string of the human-readable names.
1212      *
1213      * @param fieldNames - List of fieldNames
1214      * @return A filled StringBuffer ready to go in an error message
1215      */
1216     protected StringBuffer consolidateFieldNames(List fieldNames, String delimiter) {
1217         StringBuffer sb = new StringBuffer();
1218 
1219         // setup some vars
1220         boolean firstPass = true;
1221         String delim = "";
1222 
1223         // walk through the list
1224         for (Iterator iter = fieldNames.iterator(); iter.hasNext(); ) {
1225             String fieldName = (String) iter.next();
1226 
1227             // get the human-readable name
1228             // add the new one, with the appropriate delimiter
1229             sb.append(delim + getDataDictionaryService().getAttributeLabel(newDataObject.getClass(), fieldName));
1230 
1231             // after the first item, start using a delimiter
1232             if (firstPass) {
1233                 delim = delimiter;
1234                 firstPass = false;
1235             }
1236         }
1237 
1238         return sb;
1239     }
1240 
1241     /**
1242      * This method translates the passed in field name into a human-readable attribute label.
1243      *
1244      * It assumes the existing newDataObject's class as the class to examine the fieldName for.
1245      *
1246      * @param fieldName The fieldName you want a human-readable label for.
1247      * @return A human-readable label, pulled from the DataDictionary.
1248      */
1249     protected String getFieldLabel(String fieldName) {
1250         return getDataDictionaryService().getAttributeLabel(newDataObject.getClass(), fieldName) + "(" +
1251                 getDataDictionaryService().getAttributeShortLabel(newDataObject.getClass(), fieldName) + ")";
1252     }
1253 
1254     /**
1255      * This method translates the passed in field name into a human-readable attribute label.
1256      *
1257      * It assumes the existing newDataObject's class as the class to examine the fieldName for.
1258      *
1259      * @param dataObjectClass The class to use in combination with the fieldName.
1260      * @param fieldName The fieldName you want a human-readable label for.
1261      * @return A human-readable label, pulled from the DataDictionary.
1262      */
1263     protected String getFieldLabel(Class dataObjectClass, String fieldName) {
1264         return getDataDictionaryService().getAttributeLabel(dataObjectClass, fieldName) + "(" +
1265                 getDataDictionaryService().getAttributeShortLabel(dataObjectClass, fieldName) + ")";
1266     }
1267 
1268     /**
1269      * Gets the newDataObject attribute.
1270      *
1271      * @return Returns the newDataObject.
1272      */
1273     protected final Object getNewDataObject() {
1274         return newDataObject;
1275     }
1276 
1277     protected void setNewDataObject(Object newDataObject) {
1278         this.newDataObject = newDataObject;
1279     }
1280 
1281     /**
1282      * Gets the oldDataObject attribute.
1283      *
1284      * @return Returns the oldDataObject.
1285      */
1286     protected final Object getOldDataObject() {
1287         return oldDataObject;
1288     }
1289 
1290     public boolean processCustomAddCollectionLineBusinessRules(MaintenanceDocument document, String collectionName,
1291             PersistableBusinessObject line) {
1292         return true;
1293     }
1294 
1295     protected final BusinessObjectService getBoService() {
1296         if (boService == null) {
1297             this.boService = KRADServiceLocator.getBusinessObjectService();
1298         }
1299         return boService;
1300     }
1301 
1302     public final void setBoService(BusinessObjectService boService) {
1303         this.boService = boService;
1304     }
1305 
1306     protected final ConfigurationService getConfigService() {
1307         if (configService == null) {
1308             this.configService = KRADServiceLocator.getKualiConfigurationService();
1309         }
1310         return configService;
1311     }
1312 
1313     public final void setConfigService(ConfigurationService configService) {
1314         this.configService = configService;
1315     }
1316 
1317     protected final DataDictionaryService getDdService() {
1318         if (ddService == null) {
1319             this.ddService = KRADServiceLocatorWeb.getDataDictionaryService();
1320         }
1321         return ddService;
1322     }
1323 
1324     public final void setDdService(DataDictionaryService ddService) {
1325         this.ddService = ddService;
1326     }
1327 
1328     protected final DictionaryValidationService getDictionaryValidationService() {
1329         if (dictionaryValidationService == null) {
1330             this.dictionaryValidationService = KRADServiceLocatorWeb.getDictionaryValidationService();
1331         }
1332         return dictionaryValidationService;
1333     }
1334 
1335     public final void setDictionaryValidationService(DictionaryValidationService dictionaryValidationService) {
1336         this.dictionaryValidationService = dictionaryValidationService;
1337     }
1338 
1339     public PersonService getPersonService() {
1340         if (personService == null) {
1341             this.personService = KimApiServiceLocator.getPersonService();
1342         }
1343         return personService;
1344     }
1345 
1346     public void setPersonService(PersonService personService) {
1347         this.personService = personService;
1348     }
1349 
1350     public DateTimeService getDateTimeService() {
1351         return CoreApiServiceLocator.getDateTimeService();
1352     }
1353 
1354     protected RoleService getRoleService() {
1355         if (this.roleService == null) {
1356             this.roleService = KimApiServiceLocator.getRoleService();
1357         }
1358         return this.roleService;
1359     }
1360 
1361     protected DataObjectMetaDataService getDataObjectMetaDataService() {
1362         if (dataObjectMetaDataService == null) {
1363             this.dataObjectMetaDataService = KRADServiceLocatorWeb.getDataObjectMetaDataService();
1364         }
1365         return dataObjectMetaDataService;
1366     }
1367 
1368     public void setDataObjectMetaDataService(DataObjectMetaDataService dataObjectMetaDataService) {
1369         this.dataObjectMetaDataService = dataObjectMetaDataService;
1370     }
1371 
1372     protected final PersistenceStructureService getPersistenceStructureService() {
1373         if (persistenceStructureService == null) {
1374             this.persistenceStructureService = KRADServiceLocator.getPersistenceStructureService();
1375         }
1376         return persistenceStructureService;
1377     }
1378 
1379     public final void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) {
1380         this.persistenceStructureService = persistenceStructureService;
1381     }
1382 
1383     public WorkflowDocumentService getWorkflowDocumentService() {
1384         if (workflowDocumentService == null) {
1385             this.workflowDocumentService = KRADServiceLocatorWeb.getWorkflowDocumentService();
1386         }
1387         return workflowDocumentService;
1388     }
1389 
1390     public void setWorkflowDocumentService(WorkflowDocumentService workflowDocumentService) {
1391         this.workflowDocumentService = workflowDocumentService;
1392     }
1393 
1394     public DataObjectAuthorizationService getDataObjectAuthorizationService() {
1395         if (dataObjectAuthorizationService == null) {
1396             this.dataObjectAuthorizationService = KRADServiceLocatorWeb.getDataObjectAuthorizationService();
1397         }
1398         return dataObjectAuthorizationService;
1399     }
1400 
1401     public void setDataObjectAuthorizationService(DataObjectAuthorizationService dataObjectAuthorizationService) {
1402         this.dataObjectAuthorizationService = dataObjectAuthorizationService;
1403     }
1404 
1405 }
1406