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