Coverage Report - org.kuali.rice.kim.document.rule.IdentityManagementRoleDocumentRule
 
Classes in this File Line Coverage Branch Coverage Complexity
IdentityManagementRoleDocumentRule
0%
0/301
0%
0/232
4.308
 
 1  
 /*
 2  
  * Copyright 2007-2009 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.kim.document.rule;
 17  
 
 18  
 import org.apache.commons.lang.StringUtils;
 19  
 import org.kuali.rice.core.util.RiceKeyConstants;
 20  
 import org.kuali.rice.kim.api.permission.Permission;
 21  
 import org.kuali.rice.kim.api.responsibility.Responsibility;
 22  
 import org.kuali.rice.kim.api.responsibility.ResponsibilityService;
 23  
 import org.kuali.rice.kim.api.role.RoleService;
 24  
 import org.kuali.rice.kim.api.services.IdentityService;
 25  
 import org.kuali.rice.kim.api.services.KimApiServiceLocator;
 26  
 import org.kuali.rice.kim.api.type.KimType;
 27  
 import org.kuali.rice.kim.api.type.KimTypeService;
 28  
 import org.kuali.rice.kim.bo.types.dto.AttributeDefinitionMap;
 29  
 import org.kuali.rice.kim.bo.ui.KimDocumentRoleMember;
 30  
 import org.kuali.rice.kim.bo.ui.KimDocumentRolePermission;
 31  
 import org.kuali.rice.kim.bo.ui.KimDocumentRoleQualifier;
 32  
 import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibility;
 33  
 import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibilityAction;
 34  
 import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMember;
 35  
 import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMemberQualifier;
 36  
 import org.kuali.rice.kim.document.IdentityManagementRoleDocument;
 37  
 import org.kuali.rice.kim.framework.role.RoleEbo;
 38  
 import org.kuali.rice.kim.impl.responsibility.AddResponsibilityEvent;
 39  
 import org.kuali.rice.kim.impl.responsibility.AddResponsibilityRule;
 40  
 import org.kuali.rice.kim.impl.responsibility.KimDocumentResponsibilityRule;
 41  
 import org.kuali.rice.kim.impl.responsibility.ResponsibilityBo;
 42  
 import org.kuali.rice.kim.impl.responsibility.ResponsibilityInternalService;
 43  
 import org.kuali.rice.kim.impl.role.RoleServiceBase;
 44  
 import org.kuali.rice.kim.impl.type.KimTypeLookupableHelperServiceImpl;
 45  
 import org.kuali.rice.kim.rule.event.ui.AddDelegationEvent;
 46  
 import org.kuali.rice.kim.rule.event.ui.AddDelegationMemberEvent;
 47  
 import org.kuali.rice.kim.rule.event.ui.AddMemberEvent;
 48  
 import org.kuali.rice.kim.rule.event.ui.AddPermissionEvent;
 49  
 import org.kuali.rice.kim.rule.ui.AddDelegationMemberRule;
 50  
 import org.kuali.rice.kim.rule.ui.AddDelegationRule;
 51  
 import org.kuali.rice.kim.rule.ui.AddMemberRule;
 52  
 import org.kuali.rice.kim.rule.ui.AddPermissionRule;
 53  
 import org.kuali.rice.kim.rules.ui.KimDocumentMemberRule;
 54  
 import org.kuali.rice.kim.rules.ui.KimDocumentPermissionRule;
 55  
 import org.kuali.rice.kim.rules.ui.RoleDocumentDelegationMemberRule;
 56  
 import org.kuali.rice.kim.rules.ui.RoleDocumentDelegationRule;
 57  
 import org.kuali.rice.kim.service.KIMServiceLocatorWeb;
 58  
 import org.kuali.rice.kim.util.KimConstants;
 59  
 import org.kuali.rice.krad.datadictionary.AttributeDefinition;
 60  
 import org.kuali.rice.krad.document.Document;
 61  
 import org.kuali.rice.krad.rules.TransactionalDocumentRuleBase;
 62  
 import org.kuali.rice.krad.service.BusinessObjectService;
 63  
 import org.kuali.rice.krad.service.KRADServiceLocator;
 64  
 import org.kuali.rice.krad.util.GlobalVariables;
 65  
 import org.kuali.rice.krad.util.KRADConstants;
 66  
 import org.kuali.rice.krad.util.MessageMap;
 67  
 
 68  
 import java.sql.Timestamp;
 69  
 import java.util.Collections;
 70  
 import java.util.HashMap;
 71  
 import java.util.HashSet;
 72  
 import java.util.List;
 73  
 import java.util.Map;
 74  
 import java.util.Set;
 75  
 
 76  
 /**
 77  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 78  
  */
 79  0
 public class IdentityManagementRoleDocumentRule extends TransactionalDocumentRuleBase implements AddPermissionRule, AddResponsibilityRule, AddMemberRule, AddDelegationRule, AddDelegationMemberRule {
 80  
 //        protected static final Logger LOG = Logger.getLogger( IdentityManagementRoleDocumentRule.class );
 81  
 
 82  
     public static final int PRIORITY_NUMBER_MIN_VALUE = 1;
 83  
     public static final int PRIORITY_NUMBER_MAX_VALUE = 11;
 84  
 
 85  
         protected AddResponsibilityRule addResponsibilityRule;
 86  
         protected AddPermissionRule  addPermissionRule;
 87  
         protected AddMemberRule  addMemberRule;
 88  
         protected AddDelegationRule addDelegationRule;
 89  
         protected AddDelegationMemberRule addDelegationMemberRule;
 90  
         protected BusinessObjectService businessObjectService;
 91  
         protected ResponsibilityService responsibilityService;
 92  0
         protected Class<? extends AddResponsibilityRule> addResponsibilityRuleClass = KimDocumentResponsibilityRule.class;
 93  0
         protected Class<? extends AddPermissionRule> addPermissionRuleClass = KimDocumentPermissionRule.class;
 94  0
         protected Class<? extends AddMemberRule> addMemberRuleClass = KimDocumentMemberRule.class;
 95  0
         protected Class<? extends AddDelegationRule> addDelegationRuleClass = RoleDocumentDelegationRule.class;
 96  0
         protected Class<? extends AddDelegationMemberRule> addDelegationMemberRuleClass = RoleDocumentDelegationMemberRule.class;
 97  
 
 98  
         protected IdentityService identityService;
 99  
         private static ResponsibilityInternalService responsibilityInternalService;
 100  
 
 101  0
         protected AttributeValidationHelper attributeValidationHelper = new AttributeValidationHelper();
 102  
 
 103  
         // KULRICE-4153
 104  0
         protected ActiveRoleMemberHelper activeRoleMemberHelper = new ActiveRoleMemberHelper();
 105  
 
 106  
     public IdentityService getIdentityService() {
 107  0
         if ( identityService == null) {
 108  0
             identityService = KimApiServiceLocator.getIdentityService();
 109  
         }
 110  0
         return identityService;
 111  
     }
 112  
 
 113  
     @Override
 114  
     protected boolean processCustomSaveDocumentBusinessRules(Document document) {
 115  0
         if (!(document instanceof IdentityManagementRoleDocument)) {
 116  0
             return false;
 117  
         }
 118  
 
 119  0
         IdentityManagementRoleDocument roleDoc = (IdentityManagementRoleDocument)document;
 120  
 
 121  0
         boolean valid = true;
 122  0
         boolean validateRoleAssigneesAndDelegations = !KimTypeLookupableHelperServiceImpl
 123  
                 .hasDerivedRoleTypeService(roleDoc.getKimType());
 124  0
         GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
 125  0
         valid &= validDuplicateRoleName(roleDoc);
 126  0
         valid &= validPermissions(roleDoc);
 127  0
         valid &= validResponsibilities(roleDoc);
 128  0
         getDictionaryValidationService().validateDocumentAndUpdatableReferencesRecursively(document, getMaxDictionaryValidationDepth(), true, false);
 129  0
         validateRoleAssigneesAndDelegations &= validAssignRole(roleDoc);
 130  0
         if(validateRoleAssigneesAndDelegations){
 131  
                 //valid &= validAssignRole(roleDoc);
 132  
                 // KULRICE-4153 & KULRICE-4818
 133  
                 // Use the Active Role Member Helper to retrieve only those Role Members & Delegation member that are active
 134  
                 // If a member or delegation is active on a Role, and they have an inactive Role Qualifier, Role Qualifier validation will fail
 135  
                 // If a member or delegation is inactive on a Role, and they have an inactive Role Qualifier, Role Qualifier validation will pass
 136  0
                 List<KimDocumentRoleMember> activeRoleMembers = activeRoleMemberHelper.getActiveRoleMembers(roleDoc.getMembers());
 137  0
                 List<RoleDocumentDelegationMember> activeRoleDelegationMembers = activeRoleMemberHelper.getActiveDelegationRoleMembers(roleDoc.getDelegationMembers());
 138  
 
 139  0
                 valid &= validateRoleQualifier(activeRoleMembers, roleDoc.getKimType());
 140  0
                 valid &= validRoleMemberActiveDates(roleDoc.getMembers());
 141  0
                 valid &= validateDelegationMemberRoleQualifier(activeRoleMembers, activeRoleDelegationMembers, roleDoc.getKimType());
 142  0
                 valid &= validDelegationMemberActiveDates(roleDoc.getDelegationMembers());
 143  0
                 valid &= validRoleMembersResponsibilityActions(roleDoc.getMembers());
 144  
         }
 145  0
         valid &= validRoleResponsibilitiesActions(roleDoc.getResponsibilities());
 146  0
         GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
 147  
 
 148  0
         return valid;
 149  
     }
 150  
 
 151  
         protected boolean validAssignRole(IdentityManagementRoleDocument document){
 152  0
         boolean rulePassed = true;
 153  0
         Map<String,String> additionalPermissionDetails = new HashMap<String,String>();
 154  0
         additionalPermissionDetails.put(KimConstants.AttributeConstants.NAMESPACE_CODE, document.getRoleNamespace());
 155  0
         additionalPermissionDetails.put(KimConstants.AttributeConstants.ROLE_NAME, document.getRoleName());
 156  0
                 if((document.getMembers()!=null && document.getMembers().size()>0) ||
 157  
                                 (document.getDelegationMembers()!=null && document.getDelegationMembers().size()>0)){
 158  0
                         if(!getDocumentHelperService().getDocumentAuthorizer(document).isAuthorizedByTemplate(
 159  
                                         document, KimConstants.NAMESPACE_CODE, KimConstants.PermissionTemplateNames.ASSIGN_ROLE,
 160  
                                         GlobalVariables.getUserSession().getPrincipalId(), additionalPermissionDetails, null)){
 161  0
                     rulePassed = false;
 162  
                         }
 163  
                 }
 164  0
                 return rulePassed;
 165  
         }
 166  
 
 167  
     @SuppressWarnings("unchecked")
 168  
         protected boolean validDuplicateRoleName(IdentityManagementRoleDocument roleDoc){
 169  0
             Map<String, String> criteria = new HashMap<String, String>();
 170  0
             criteria.put("roleName", roleDoc.getRoleName());
 171  0
             criteria.put("namespaceCode", roleDoc.getRoleNamespace());
 172  0
             List<RoleEbo> roleEboList = (List<RoleEbo>) getBusinessObjectService().findMatching(RoleEbo.class, criteria);
 173  0
             boolean rulePassed = true;
 174  0
             if(roleEboList!=null && roleEboList.size()>0){
 175  0
                     if(roleEboList.size()==1 && roleEboList.get(0).getId().equals(roleDoc.getRoleId())) {
 176  0
                 rulePassed = true;
 177  
             }
 178  
                     else{
 179  0
                             GlobalVariables.getMessageMap().putError("document.roleName",
 180  
                                             RiceKeyConstants.ERROR_DUPLICATE_ENTRY, new String[] {"Role Name"});
 181  0
                             rulePassed = false;
 182  
                     }
 183  
             }
 184  0
             return rulePassed;
 185  
     }
 186  
 
 187  
     protected boolean validRoleMemberActiveDates(List<KimDocumentRoleMember> roleMembers) {
 188  0
             boolean valid = true;
 189  0
                 int i = 0;
 190  0
             for(KimDocumentRoleMember roleMember: roleMembers) {
 191  0
                            valid &= validateActiveDate("document.members["+i+"].activeToDate", roleMember.getActiveFromDate(), roleMember.getActiveToDate());
 192  0
                     i++;
 193  
             }
 194  0
             return valid;
 195  
     }
 196  
 
 197  
     protected boolean validDelegationMemberActiveDates(List<RoleDocumentDelegationMember> delegationMembers) {
 198  0
             boolean valid = true;
 199  0
                 int i = 0;
 200  0
             for(RoleDocumentDelegationMember delegationMember: delegationMembers) {
 201  0
                            valid &= validateActiveDate("document.delegationMembers[" + i + "].activeToDate",
 202  
                        delegationMember.getActiveFromDate(), delegationMember.getActiveToDate());
 203  0
                     i++;
 204  
             }
 205  0
             return valid;
 206  
     }
 207  
 
 208  
     protected boolean validPermissions(IdentityManagementRoleDocument document){
 209  
             Permission kimPermissionInfo;
 210  0
             boolean valid = true;
 211  0
             int i = 0;
 212  0
             for(KimDocumentRolePermission permission: document.getPermissions()){
 213  0
                     kimPermissionInfo = permission.getPermission();
 214  0
                     if(!permission.isActive() && !hasPermissionToGrantPermission(permission.getPermission(), document)){
 215  0
                     GlobalVariables.getMessageMap().putError("permissions["+i+"].active", RiceKeyConstants.ERROR_ASSIGN_PERMISSION,
 216  
                                     new String[] {kimPermissionInfo.getNamespaceCode(), kimPermissionInfo.getTemplate().getName()});
 217  0
                     valid = false;
 218  
                     }
 219  0
                     i++;
 220  
             }
 221  0
             return valid;
 222  
     }
 223  
 
 224  
     protected boolean validResponsibilities(IdentityManagementRoleDocument document){
 225  
             ResponsibilityBo kimResponsibilityImpl;
 226  0
             boolean valid = true;
 227  0
             int i = 0;
 228  0
             for(KimDocumentRoleResponsibility responsibility: document.getResponsibilities()){
 229  0
                     kimResponsibilityImpl = responsibility.getKimResponsibility();
 230  0
                     if(!responsibility.isActive() && !hasPermissionToGrantResponsibility(ResponsibilityBo.to(responsibility.getKimResponsibility()), document)){
 231  0
                     GlobalVariables.getMessageMap().putError("responsibilities["+i+"].active", RiceKeyConstants.ERROR_ASSIGN_RESPONSIBILITY,
 232  
                                     new String[] {kimResponsibilityImpl.getNamespaceCode(), kimResponsibilityImpl.getTemplate().getName()});
 233  0
                     valid = false;
 234  
                     }
 235  0
                     i++;
 236  
             }
 237  0
             return valid;
 238  
     }
 239  
 
 240  
     protected boolean validRoleResponsibilitiesActions(List<KimDocumentRoleResponsibility> roleResponsibilities){
 241  0
         int i = 0;
 242  0
         boolean rulePassed = true;
 243  0
             for(KimDocumentRoleResponsibility roleResponsibility: roleResponsibilities){
 244  0
                     if(!getResponsibilityInternalService().areActionsAtAssignmentLevelById(roleResponsibility.getResponsibilityId())) {
 245  0
                             validateRoleResponsibilityAction("document.responsibilities["+i+"].roleRspActions[0].priorityNumber", roleResponsibility.getRoleRspActions().get(0));
 246  
             }
 247  0
                 i++;
 248  
             }
 249  0
             return rulePassed;
 250  
     }
 251  
 
 252  
     protected boolean validRoleMembersResponsibilityActions(List<KimDocumentRoleMember> roleMembers){
 253  0
         int i = 0;
 254  
         int j;
 255  0
         boolean rulePassed = true;
 256  0
             for(KimDocumentRoleMember roleMember: roleMembers){
 257  0
                     j = 0;
 258  0
                     if(roleMember.getRoleRspActions()!=null && !roleMember.getRoleRspActions().isEmpty()){
 259  0
                             for(KimDocumentRoleResponsibilityAction roleRspAction: roleMember.getRoleRspActions()){
 260  0
                                     validateRoleResponsibilityAction("document.members["+i+"].roleRspActions["+j+"].priorityNumber", roleRspAction);
 261  0
                                 j++;
 262  
                             }
 263  
                     }
 264  0
                     i++;
 265  
             }
 266  0
             return rulePassed;
 267  
     }
 268  
 
 269  
     protected boolean validateRoleResponsibilityAction(String errorPath, KimDocumentRoleResponsibilityAction roleRspAction){
 270  0
             boolean rulePassed = true;
 271  
             /*if(StringUtils.isBlank(roleRspAction.getActionPolicyCode())){
 272  
                     GlobalVariables.getErrorMap().putError(errorPath,
 273  
                                     RiceKeyConstants.ERROR_EMPTY_ENTRY, new String[] {"Action Policy Code"});
 274  
                     rulePassed = false;
 275  
             }
 276  
             if(roleRspAction.getPriorityNumber()==null){
 277  
                     GlobalVariables.getErrorMap().putError(errorPath,
 278  
                                     RiceKeyConstants.ERROR_EMPTY_ENTRY, new String[] {"Priority Number"});
 279  
                     rulePassed = false;
 280  
             }
 281  
             if(StringUtils.isBlank(roleRspAction.getActionTypeCode())){
 282  
                     GlobalVariables.getErrorMap().putError(errorPath,
 283  
                                     RiceKeyConstants.ERROR_EMPTY_ENTRY, new String[] {"Action Type Code"});
 284  
                     rulePassed = false;
 285  
             }*/
 286  0
             if(roleRspAction.getPriorityNumber()!=null &&
 287  
                             (roleRspAction.getPriorityNumber()<PRIORITY_NUMBER_MIN_VALUE
 288  
                                             || roleRspAction.getPriorityNumber()>PRIORITY_NUMBER_MAX_VALUE)){
 289  0
                     GlobalVariables.getMessageMap().putError(errorPath,
 290  
                                    RiceKeyConstants.ERROR_PRIORITY_NUMBER_RANGE, new String[] {PRIORITY_NUMBER_MIN_VALUE+"", PRIORITY_NUMBER_MAX_VALUE+""});
 291  0
                     rulePassed = false;
 292  
             }
 293  
 
 294  0
             return rulePassed;
 295  
     }
 296  
 
 297  
     protected boolean validateRoleQualifier(List<KimDocumentRoleMember> roleMembers, KimType kimType){
 298  0
                 Map<String, String> validationErrors = new HashMap<String, String>();
 299  
 
 300  0
                 int memberCounter = 0;
 301  0
                 int roleMemberCount = 0;
 302  
                 Map<String, String> errorsTemp;
 303  
                 Map<String, String> mapToValidate;
 304  0
         KimTypeService kimTypeService = KIMServiceLocatorWeb.getKimTypeService(kimType);
 305  0
         GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
 306  0
         final AttributeDefinitionMap attributeDefinitions = kimTypeService.getAttributeDefinitions(kimType.getId());
 307  0
         final Set<String> uniqueAttributeNames = figureOutUniqueQualificationSet(roleMembers, attributeDefinitions);
 308  
 
 309  0
                 for(KimDocumentRoleMember roleMember: roleMembers) {
 310  0
                         errorsTemp = Collections.emptyMap();
 311  0
                         mapToValidate = attributeValidationHelper.convertQualifiersToMap(roleMember.getQualifiers());
 312  0
                         if(!roleMember.isRole()){
 313  0
                                 errorsTemp = kimTypeService.validateAttributes(kimType.getId(), mapToValidate);
 314  0
                                 validationErrors.putAll( 
 315  
                                                 attributeValidationHelper.convertErrorsForMappedFields(
 316  
                                 "document.members[" + memberCounter + "]", errorsTemp));
 317  0
                         memberCounter++;
 318  
                         }
 319  0
                         if (uniqueAttributeNames.size() > 0) {
 320  0
                                 validateUniquePersonRoleQualifiersUniqueForRoleMembership(roleMember, roleMemberCount, roleMembers, uniqueAttributeNames, validationErrors);
 321  
                         }
 322  
 
 323  0
                         roleMemberCount += 1;
 324  
             }
 325  
 
 326  0
                 GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
 327  
 
 328  0
             if (validationErrors.isEmpty()) {
 329  0
                     return true;
 330  
             } 
 331  0
             attributeValidationHelper.moveValidationErrorsToErrorMap(validationErrors);
 332  0
             return false;
 333  
     }
 334  
 
 335  
     /**
 336  
      * Finds the names of the unique qualification attributes which this role should be checking against
 337  
      *
 338  
      * @param memberships the memberships (we take the qualification from the first)
 339  
      * @param attributeDefinitions information about the attributeDefinitions
 340  
      * @return a Set of unique attribute ids (with their indices, for error reporting)
 341  
      */
 342  
     protected Set<String> figureOutUniqueQualificationSet(List<KimDocumentRoleMember> memberships, AttributeDefinitionMap attributeDefinitions) {
 343  0
             Set<String> uniqueAttributeIds = new HashSet<String>();
 344  
 
 345  0
             if (memberships != null && memberships.size() > 1) { // if there aren't two or more members, doing this whole check is kinda silly
 346  0
                     KimDocumentRoleMember membership = memberships.get(0);
 347  
 
 348  0
                     for (KimDocumentRoleQualifier qualifier : membership.getQualifiers()) {
 349  0
                         if (qualifier != null && qualifier.getKimAttribute() != null && !StringUtils.isBlank(qualifier.getKimAttribute().getAttributeName())) {
 350  0
                                 final AttributeDefinition relatedDefinition = attributeDefinitions.getByAttributeName(qualifier.getKimAttribute().getAttributeName());
 351  
 
 352  0
                                 if (relatedDefinition != null && relatedDefinition.getUnique() != null && relatedDefinition.getUnique().booleanValue()) {
 353  0
                                         uniqueAttributeIds.add(qualifier.getKimAttrDefnId()); // it's unique - add it to the Set
 354  
                                 }
 355  0
                         }
 356  
                     }
 357  
             }
 358  
 
 359  0
             return uniqueAttributeIds;
 360  
     }
 361  
 
 362  
     /**
 363  
      * Checks all the qualifiers for the given membership, so that all qualifiers which should be unique are guaranteed to be unique
 364  
      *
 365  
      * @param membershipToCheck the membership to check
 366  
      * @param membershipToCheckIndex the index of the person's membership in the role (for error reporting purposes)
 367  
      * @param validationErrors Map<String, String> of errors to report
 368  
      * @return true if all unique values are indeed unique, false otherwise
 369  
      */
 370  
     protected boolean validateUniquePersonRoleQualifiersUniqueForRoleMembership(KimDocumentRoleMember membershipToCheck, int membershipToCheckIndex, List<KimDocumentRoleMember> memberships, Set<String> uniqueQualifierIds, Map<String, String> validationErrors) {
 371  0
             boolean foundError = false;
 372  0
             int count = 0;
 373  
 
 374  0
             for (KimDocumentRoleMember membership : memberships) {
 375  0
                     if (membershipToCheckIndex != count) {
 376  0
                             if (sameMembership(membershipToCheck, membership)) {
 377  0
                                     if (sameUniqueMembershipQualifications(membershipToCheck, membership, uniqueQualifierIds)) {
 378  0
                                             foundError = true;
 379  
                                             // add error to each qualifier which is supposed to be unique
 380  0
                                             int qualifierCount = 0;
 381  
 
 382  0
                                             for (KimDocumentRoleQualifier qualifier : membership.getQualifiers()) {
 383  0
                                                     if (qualifier != null && uniqueQualifierIds.contains(qualifier.getKimAttrDefnId())) {
 384  0
                                                             validationErrors.put("document.members["+membershipToCheckIndex+"].qualifiers["+qualifierCount+"].attrVal", RiceKeyConstants.ERROR_DOCUMENT_IDENTITY_MANAGEMENT_PERSON_QUALIFIER_VALUE_NOT_UNIQUE+":"+qualifier.getKimAttribute().getAttributeName()+";"+qualifier.getAttrVal());
 385  
                                                     }
 386  0
                                                     qualifierCount += 1;
 387  
                                             }
 388  
                                     }
 389  
                             }
 390  
                     }
 391  0
                     count += 1;
 392  
             }
 393  
 
 394  0
             return foundError;
 395  
     }
 396  
 
 397  
     /**
 398  
      * Determines if two memberships represent the same member being added: that is, the two memberships have the same type code and id
 399  
      *
 400  
      * @param membershipA the first membership to check
 401  
      * @param membershipB the second membership to check
 402  
      * @return true if the two memberships represent the same member; false if they do not, or if it could not be profitably determined if the members were the same
 403  
      */
 404  
     protected boolean sameMembership(KimDocumentRoleMember membershipA, KimDocumentRoleMember membershipB) {
 405  0
             if (!StringUtils.isBlank(membershipA.getMemberTypeCode()) && !StringUtils.isBlank(membershipB.getMemberTypeCode()) && !StringUtils.isBlank(membershipA.getMemberId()) && !StringUtils.isBlank(membershipB.getMemberId())) {
 406  0
                     return membershipA.getMemberTypeCode().equals(membershipB.getMemberTypeCode()) && membershipA.getMemberId().equals(membershipB.getMemberId());
 407  
             }
 408  0
             return false;
 409  
     }
 410  
 
 411  
     /**
 412  
      * Given two memberships which represent the same member, do they share qualifications?
 413  
      *
 414  
      * @param membershipA the first membership to check
 415  
      * @param membershipB the second membership to check
 416  
      * @param uniqueAttributeIds the Set of attribute definition ids which should be unique
 417  
      * @return
 418  
      */
 419  
     protected boolean sameUniqueMembershipQualifications(KimDocumentRoleMember membershipA, KimDocumentRoleMember membershipB, Set<String> uniqueAttributeIds) {
 420  0
             boolean equalSoFar = true;
 421  0
             for (String kimAttributeDefinitionId : uniqueAttributeIds) {
 422  0
                     final KimDocumentRoleQualifier qualifierA = membershipA.getQualifier(kimAttributeDefinitionId);
 423  0
                     final KimDocumentRoleQualifier qualifierB = membershipB.getQualifier(kimAttributeDefinitionId);
 424  
 
 425  0
                     if (qualifierA != null && qualifierB != null) {
 426  0
                             equalSoFar &= (qualifierA.getAttrVal() == null && qualifierB.getAttrVal() == null) || (qualifierA.getAttrVal() == null || qualifierA.getAttrVal().equals(qualifierB.getAttrVal()));
 427  
                     }
 428  0
             }
 429  0
             return equalSoFar;
 430  
     }
 431  
 
 432  
     protected KimDocumentRoleMember getRoleMemberForDelegation(
 433  
                     List<KimDocumentRoleMember> roleMembers, RoleDocumentDelegationMember delegationMember){
 434  0
             if(roleMembers==null || delegationMember==null || delegationMember.getRoleMemberId()==null) { return null; }
 435  0
             for(KimDocumentRoleMember roleMember: roleMembers){
 436  0
                     if(delegationMember.getRoleMemberId().equals(roleMember.getRoleMemberId())) {
 437  0
                 return roleMember;
 438  
             }
 439  
             }
 440  0
             return null;
 441  
     }
 442  
 
 443  
     protected boolean validateDelegationMemberRoleQualifier(List<KimDocumentRoleMember> roleMembers,
 444  
                     List<RoleDocumentDelegationMember> delegationMembers, KimType kimType){
 445  0
                 Map<String, String> validationErrors = new HashMap<String, String>();
 446  
                 boolean valid;
 447  0
                 int memberCounter = 0;
 448  
                 Map<String, String> errorsTemp;
 449  
                 Map<String, String> mapToValidate;
 450  0
         KimTypeService kimTypeService = KIMServiceLocatorWeb.getKimTypeService(kimType);
 451  0
         GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
 452  
         KimDocumentRoleMember roleMember;
 453  
         String errorPath;
 454  0
         final AttributeDefinitionMap attributeDefinitions = kimTypeService.getAttributeDefinitions(kimType.getId());
 455  0
         final Set<String> uniqueQualifierAttributes = figureOutUniqueQualificationSetForDelegation(delegationMembers, attributeDefinitions);
 456  
 
 457  0
                 for(RoleDocumentDelegationMember delegationMember: delegationMembers) {
 458  0
                         errorPath = "delegationMembers["+memberCounter+"]";
 459  0
                         mapToValidate = attributeValidationHelper.convertQualifiersToMap(delegationMember.getQualifiers());
 460  0
                         if(!delegationMember.isRole()){
 461  0
                                 errorsTemp = kimTypeService.validateAttributes(kimType.getId(), mapToValidate);
 462  0
                                 validationErrors.putAll(
 463  
                                                 attributeValidationHelper.convertErrorsForMappedFields(errorPath, errorsTemp));
 464  
                         }
 465  0
                         roleMember = getRoleMemberForDelegation(roleMembers, delegationMember);
 466  0
                         if(roleMember==null){
 467  0
                                 valid = false;
 468  0
                                 GlobalVariables.getMessageMap().putError("document.delegationMembers["+memberCounter+"]", RiceKeyConstants.ERROR_DELEGATE_ROLE_MEMBER_ASSOCIATION, new String[]{});
 469  
                         } else{
 470  0
                                 errorsTemp = kimTypeService.validateUnmodifiableAttributes(
 471  
                                                                 kimType.getId(),
 472  
                                                                 attributeValidationHelper.convertQualifiersToMap(roleMember.getQualifiers()),
 473  
                                                                 mapToValidate);
 474  0
                                 validationErrors.putAll(
 475  
                                                 attributeValidationHelper.convertErrorsForMappedFields(errorPath, errorsTemp) );
 476  
                         }
 477  0
                         if (uniqueQualifierAttributes.size() > 0) {
 478  0
                                 validateUniquePersonRoleQualifiersUniqueForRoleDelegation(delegationMember, memberCounter, delegationMembers, uniqueQualifierAttributes, validationErrors);
 479  
                         }
 480  0
                 memberCounter++;
 481  
             }
 482  0
                 GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
 483  0
             if (validationErrors.isEmpty()) {
 484  0
                     valid = true;
 485  
             } else {
 486  0
                     attributeValidationHelper.moveValidationErrorsToErrorMap(validationErrors);
 487  0
                     valid = false;
 488  
             }
 489  0
             return valid;
 490  
     }
 491  
 
 492  
     /**
 493  
      * Finds the names of the unique qualification attributes which this role should be checking against
 494  
      *
 495  
      * @param memberships the memberships (we take the qualification from the first)
 496  
      * @param attributeDefinitions information about the attributeDefinitions
 497  
      * @return a Set of unique attribute ids (with their indices, for error reporting)
 498  
      */
 499  
     protected Set<String> figureOutUniqueQualificationSetForDelegation(List<RoleDocumentDelegationMember> memberships, AttributeDefinitionMap attributeDefinitions) {
 500  0
             Set<String> uniqueAttributeIds = new HashSet<String>();
 501  
 
 502  0
             if (memberships != null && memberships.size() > 1) { // if there aren't two or more members, doing this whole check is kinda silly
 503  0
                     RoleDocumentDelegationMember membership = memberships.get(0);
 504  
 
 505  0
                     for (RoleDocumentDelegationMemberQualifier qualifier : membership.getQualifiers()) {
 506  0
                         if (qualifier != null && qualifier.getKimAttribute() != null && !StringUtils.isBlank(qualifier.getKimAttribute().getAttributeName())) {
 507  0
                                 final AttributeDefinition relatedDefinition = attributeDefinitions.getByAttributeName(qualifier.getKimAttribute().getAttributeName());
 508  
 
 509  0
                                 if (relatedDefinition.getUnique() != null && relatedDefinition.getUnique().booleanValue()) {
 510  0
                                         uniqueAttributeIds.add(qualifier.getKimAttrDefnId()); // it's unique - add it to the Set
 511  
                                 }
 512  0
                         }
 513  
                     }
 514  
             }
 515  
 
 516  0
             return uniqueAttributeIds;
 517  
     }
 518  
 
 519  
     /**
 520  
      * Checks all the qualifiers for the given membership, so that all qualifiers which should be unique are guaranteed to be unique
 521  
      *
 522  
      * @param delegationMembershipToCheck the membership to check
 523  
      * @param membershipToCheckIndex the index of the person's membership in the role (for error reporting purposes)
 524  
      * @param validationErrors Map<String, String> of errors to report
 525  
      * @return true if all unique values are indeed unique, false otherwise
 526  
      */
 527  
     protected boolean validateUniquePersonRoleQualifiersUniqueForRoleDelegation(RoleDocumentDelegationMember delegationMembershipToCheck, int membershipToCheckIndex, List<RoleDocumentDelegationMember> delegationMemberships, Set<String> uniqueQualifierIds, Map<String, String> validationErrors) {
 528  0
             boolean foundError = false;
 529  0
             int count = 0;
 530  
 
 531  0
             for (RoleDocumentDelegationMember delegationMembership : delegationMemberships) {
 532  0
                     if (membershipToCheckIndex != count) {
 533  0
                             if (sameDelegationMembership(delegationMembershipToCheck, delegationMembership)) {
 534  0
                                     if (sameUniqueDelegationMembershipQualifications(delegationMembershipToCheck, delegationMembership, uniqueQualifierIds)) {
 535  0
                                             foundError = true;
 536  
                                             // add error to each qualifier which is supposed to be unique
 537  0
                                             int qualifierCount = 0;
 538  
 
 539  0
                                             for (RoleDocumentDelegationMemberQualifier qualifier : delegationMembership.getQualifiers()) {
 540  0
                                                     if (qualifier != null && uniqueQualifierIds.contains(qualifier.getKimAttrDefnId())) {
 541  0
                                                             validationErrors.put("document.delegationMembers["+membershipToCheckIndex+"].qualifiers["+qualifierCount+"].attrVal", RiceKeyConstants.ERROR_DOCUMENT_IDENTITY_MANAGEMENT_PERSON_QUALIFIER_VALUE_NOT_UNIQUE+":"+qualifier.getKimAttribute().getAttributeName()+";"+qualifier.getAttrVal());
 542  
                                                     }
 543  0
                                                     qualifierCount += 1;
 544  
                                             }
 545  
                                     }
 546  
                             }
 547  
                     }
 548  0
                     count += 1;
 549  
             }
 550  
 
 551  0
             return foundError;
 552  
     }
 553  
 
 554  
     /**
 555  
      * Determines if two memberships represent the same member being added: that is, the two memberships have the same type code and id
 556  
      *
 557  
      * @param membershipA the first membership to check
 558  
      * @param membershipB the second membership to check
 559  
      * @return true if the two memberships represent the same member; false if they do not, or if it could not be profitably determined if the members were the same
 560  
      */
 561  
     protected boolean sameDelegationMembership(RoleDocumentDelegationMember membershipA, RoleDocumentDelegationMember membershipB) {
 562  0
             if (!StringUtils.isBlank(membershipA.getMemberTypeCode()) && !StringUtils.isBlank(membershipB.getMemberTypeCode()) && !StringUtils.isBlank(membershipA.getMemberId()) && !StringUtils.isBlank(membershipB.getMemberId())) {
 563  0
                     return membershipA.getMemberTypeCode().equals(membershipB.getMemberTypeCode()) && membershipA.getMemberId().equals(membershipB.getMemberId());
 564  
             }
 565  0
             return false;
 566  
     }
 567  
 
 568  
     /**
 569  
      * Given two memberships which represent the same member, do they share qualifications?
 570  
      *
 571  
      * @param membershipA the first membership to check
 572  
      * @param membershipB the second membership to check
 573  
      * @param uniqueAttributeIds the Set of attribute definition ids which should be unique
 574  
      * @return
 575  
      */
 576  
     protected boolean sameUniqueDelegationMembershipQualifications(RoleDocumentDelegationMember membershipA, RoleDocumentDelegationMember membershipB, Set<String> uniqueAttributeIds) {
 577  0
             boolean equalSoFar = true;
 578  0
             for (String kimAttributeDefinitionId : uniqueAttributeIds) {
 579  0
                     final RoleDocumentDelegationMemberQualifier qualifierA = membershipA.getQualifier(kimAttributeDefinitionId);
 580  0
                     final RoleDocumentDelegationMemberQualifier qualifierB = membershipB.getQualifier(kimAttributeDefinitionId);
 581  
 
 582  0
                     if (qualifierA != null && qualifierB != null) {
 583  0
                             equalSoFar &= (qualifierA.getAttrVal() == null && qualifierB.getAttrVal() == null) || (qualifierA.getAttrVal() == null || qualifierA.getAttrVal().equals(qualifierB.getAttrVal()));
 584  
                     }
 585  0
             }
 586  0
             return equalSoFar;
 587  
     }
 588  
 
 589  
         protected boolean validateActiveDate(String errorPath, Timestamp activeFromDate, Timestamp activeToDate) {
 590  
                 // TODO : do not have detail bus rule yet, so just check this for now.
 591  0
                 boolean valid = true;
 592  0
                 if (activeFromDate != null && activeToDate !=null && activeToDate.before(activeFromDate)) {
 593  0
                 MessageMap errorMap = GlobalVariables.getMessageMap();
 594  0
             errorMap.putError(errorPath, RiceKeyConstants.ERROR_ACTIVE_TO_DATE_BEFORE_FROM_DATE);
 595  0
             valid = false;
 596  
 
 597  
                 }
 598  0
                 return valid;
 599  
         }
 600  
 
 601  
         /**
 602  
          *
 603  
          * This method checks to see if adding a role to role membership
 604  
          * creates a circular reference.
 605  
          *
 606  
          * @param addMemberEvent
 607  
          * @return true  - ok to assign, no circular references
 608  
          *         false - do not make assignment, will create circular reference.
 609  
          */
 610  
         protected boolean checkForCircularRoleMembership(AddMemberEvent addMemberEvent)
 611  
         {
 612  0
                 KimDocumentRoleMember newMember = addMemberEvent.getMember();
 613  0
                 if (newMember == null || StringUtils.isBlank(newMember.getMemberId())){
 614  0
                         MessageMap errorMap = GlobalVariables.getMessageMap();
 615  0
                         errorMap.putError("member.memberId", RiceKeyConstants.ERROR_INVALID_ROLE, new String[] {""});
 616  0
                         return false;
 617  
                 }
 618  0
                 Set<String> roleMemberIds = null;
 619  
                 // if the role member is a role, check to make sure we won't be creating a circular reference.
 620  
                 // Verify that the new role is not already related to the role either directly or indirectly
 621  0
                 if (newMember.isRole()){
 622  
                         // get all nested role member ids that are of type role
 623  0
                         RoleService roleService = KimApiServiceLocator.getRoleService();
 624  0
                         roleMemberIds = ((RoleServiceBase) roleService).getRoleTypeRoleMemberIds(newMember.getMemberId());
 625  
 
 626  
                         // check to see if the document role is not a member of the new member role
 627  0
                         IdentityManagementRoleDocument document = (IdentityManagementRoleDocument)addMemberEvent.getDocument();
 628  0
                         if (roleMemberIds.contains(document.getRoleId())){
 629  0
                                 MessageMap errorMap = GlobalVariables.getMessageMap();
 630  0
                                 errorMap.putError("member.memberId", RiceKeyConstants.ERROR_ASSIGN_ROLE_MEMBER_CIRCULAR, new String[] {newMember.getMemberId()});
 631  0
                                 return false;
 632  
                         }
 633  
                 }
 634  0
                 return true;
 635  
         }
 636  
 
 637  
         /**
 638  
          * @return the addResponsibilityRule
 639  
          */
 640  
         public AddResponsibilityRule getAddResponsibilityRule() {
 641  0
                 if(addResponsibilityRule == null){
 642  
                         try {
 643  0
                                 addResponsibilityRule = addResponsibilityRuleClass.newInstance();
 644  0
                         } catch ( Exception ex ) {
 645  0
                                 throw new RuntimeException( "Unable to create AddResponsibilityRule instance using class: " + addResponsibilityRuleClass, ex );
 646  0
                         }
 647  
                 }
 648  0
                 return addResponsibilityRule;
 649  
         }
 650  
 
 651  
         /**
 652  
          * @return the addPermissionRule
 653  
          */
 654  
         public AddPermissionRule getAddPermissionRule() {
 655  0
                 if(addPermissionRule == null){
 656  
                         try {
 657  0
                                 addPermissionRule = addPermissionRuleClass.newInstance();
 658  0
                         } catch ( Exception ex ) {
 659  0
                                 throw new RuntimeException( "Unable to create AddPermissionRule instance using class: " + addPermissionRuleClass, ex );
 660  0
                         }
 661  
                 }
 662  0
                 return addPermissionRule;
 663  
         }
 664  
 
 665  
         /**
 666  
          * @return the addMemberRule
 667  
          */
 668  
         public AddMemberRule getAddMemberRule() {
 669  0
                 if(addMemberRule == null){
 670  
                         try {
 671  0
                                 addMemberRule = addMemberRuleClass.newInstance();
 672  0
                         } catch ( Exception ex ) {
 673  0
                                 throw new RuntimeException( "Unable to create AddMemberRule instance using class: " + addMemberRuleClass, ex );
 674  0
                         }
 675  
                 }
 676  0
                 return addMemberRule;
 677  
         }
 678  
 
 679  
         /**
 680  
          * @return the addDelegationRule
 681  
          */
 682  
         public AddDelegationRule getAddDelegationRule() {
 683  0
                 if(addDelegationRule == null){
 684  
                         try {
 685  0
                                 addDelegationRule = addDelegationRuleClass.newInstance();
 686  0
                         } catch ( Exception ex ) {
 687  0
                                 throw new RuntimeException( "Unable to create AddDelegationRule instance using class: " + addDelegationRuleClass, ex );
 688  0
                         }
 689  
                 }
 690  0
                 return addDelegationRule;
 691  
         }
 692  
 
 693  
         /**
 694  
          * @return the addDelegationMemberRule
 695  
          */
 696  
         public AddDelegationMemberRule getAddDelegationMemberRule() {
 697  0
                 if(addDelegationMemberRule == null){
 698  
                         try {
 699  0
                                 addDelegationMemberRule = addDelegationMemberRuleClass.newInstance();
 700  0
                         } catch ( Exception ex ) {
 701  0
                                 throw new RuntimeException( "Unable to create AddDelegationMemberRule instance using class: " + addDelegationMemberRuleClass, ex );
 702  0
                         }
 703  
                 }
 704  0
                 return addDelegationMemberRule;
 705  
         }
 706  
 
 707  
     public boolean processAddPermission(AddPermissionEvent addPermissionEvent) {
 708  0
         return getAddPermissionRule().processAddPermission(addPermissionEvent);
 709  
     }
 710  
 
 711  
     public boolean hasPermissionToGrantPermission(Permission kimPermissionInfo , IdentityManagementRoleDocument document){
 712  0
         return getAddPermissionRule().hasPermissionToGrantPermission(kimPermissionInfo, document);
 713  
     }
 714  
 
 715  
     public boolean processAddResponsibility(AddResponsibilityEvent addResponsibilityEvent) {
 716  0
         return getAddResponsibilityRule().processAddResponsibility(addResponsibilityEvent);
 717  
     }
 718  
 
 719  
     public boolean hasPermissionToGrantResponsibility(Responsibility kimResponsibilityInfo, IdentityManagementRoleDocument document) {
 720  0
         return getAddResponsibilityRule().hasPermissionToGrantResponsibility(kimResponsibilityInfo, document);
 721  
     }
 722  
 
 723  
     public boolean processAddMember(AddMemberEvent addMemberEvent) {
 724  0
         boolean success = new KimDocumentMemberRule().processAddMember(addMemberEvent);
 725  0
         success &= validateActiveDate("member.activeFromDate", addMemberEvent.getMember().getActiveFromDate(), addMemberEvent.getMember().getActiveToDate());
 726  0
         success &= checkForCircularRoleMembership(addMemberEvent);
 727  0
         return success;
 728  
     }
 729  
 
 730  
     public boolean processAddDelegation(AddDelegationEvent addDelegationEvent) {
 731  0
         return getAddDelegationRule().processAddDelegation(addDelegationEvent);
 732  
     }
 733  
 
 734  
     public boolean processAddDelegationMember(AddDelegationMemberEvent addDelegationMemberEvent) {
 735  0
         boolean success = new RoleDocumentDelegationMemberRule().processAddDelegationMember(addDelegationMemberEvent);
 736  0
         RoleDocumentDelegationMember roleDocumentDelegationMember = addDelegationMemberEvent.getDelegationMember();
 737  0
         success &= validateActiveDate("delegationMember.activeFromDate", roleDocumentDelegationMember.getActiveFromDate(), roleDocumentDelegationMember.getActiveToDate());
 738  0
         return success;
 739  
     }
 740  
 
 741  
         public ResponsibilityService getResponsibilityService() {
 742  0
                 if(responsibilityService == null){
 743  0
                         responsibilityService = KimApiServiceLocator.getResponsibilityService();
 744  
                 }
 745  0
                 return responsibilityService;
 746  
         }
 747  
 
 748  
     public ResponsibilityInternalService getResponsibilityInternalService() {
 749  0
             if ( responsibilityInternalService == null ) {
 750  0
                     responsibilityInternalService = org.kuali.rice.kim.impl.services.KIMServiceLocatorInternal.getResponsibilityInternalService();
 751  
             }
 752  0
                 return responsibilityInternalService;
 753  
         }
 754  
 
 755  
 
 756  
         /**
 757  
          * @return the businessObjectService
 758  
          */
 759  
         public BusinessObjectService getBusinessObjectService() {
 760  0
                 if(businessObjectService == null){
 761  0
                         businessObjectService = KRADServiceLocator.getBusinessObjectService();
 762  
                 }
 763  0
                 return businessObjectService;
 764  
         }
 765  
 }