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