View Javadoc

1   /**
2    * Copyright 2005-2013 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.collections.CollectionUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.kuali.rice.core.api.membership.MemberType;
21  import org.kuali.rice.core.api.uif.RemotableAttributeError;
22  import org.kuali.rice.core.api.util.RiceKeyConstants;
23  import org.kuali.rice.kim.api.KimConstants;
24  import org.kuali.rice.kim.api.group.Group;
25  import org.kuali.rice.kim.api.identity.IdentityService;
26  import org.kuali.rice.kim.api.identity.principal.Principal;
27  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
28  import org.kuali.rice.kim.api.type.KimType;
29  import org.kuali.rice.kim.bo.ui.GroupDocumentMember;
30  import org.kuali.rice.kim.bo.ui.GroupDocumentQualifier;
31  import org.kuali.rice.kim.document.IdentityManagementGroupDocument;
32  import org.kuali.rice.kim.framework.services.KimFrameworkServiceLocator;
33  import org.kuali.rice.kim.framework.type.KimTypeService;
34  import org.kuali.rice.kim.rule.event.ui.AddGroupMemberEvent;
35  import org.kuali.rice.kim.rule.ui.AddGroupMemberRule;
36  import org.kuali.rice.kim.rules.ui.GroupDocumentMemberRule;
37  import org.kuali.rice.krad.document.Document;
38  import org.kuali.rice.kns.rules.TransactionalDocumentRuleBase;
39  import org.kuali.rice.krad.service.BusinessObjectService;
40  import org.kuali.rice.krad.service.KRADServiceLocator;
41  import org.kuali.rice.krad.util.GlobalVariables;
42  import org.kuali.rice.krad.util.KRADConstants;
43  import org.kuali.rice.krad.util.MessageMap;
44  
45  import java.sql.Timestamp;
46  import java.util.ArrayList;
47  import java.util.Collection;
48  import java.util.HashMap;
49  import java.util.List;
50  import java.util.Map;
51  
52  /**
53   * @author Kuali Rice Team (rice.collab@kuali.org)
54   */
55  public class IdentityManagementGroupDocumentRule extends TransactionalDocumentRuleBase implements AddGroupMemberRule {
56  
57  	protected AddGroupMemberRule addGroupMemberRule;
58  	protected AttributeValidationHelper attributeValidationHelper = new AttributeValidationHelper();
59  	
60  	protected BusinessObjectService businessObjectService;
61  	protected Class<? extends GroupDocumentMemberRule> addGroupMemberRuleClass = GroupDocumentMemberRule.class;
62  
63  	protected IdentityService identityService; 
64  	
65      public IdentityService getIdentityService() {
66          if ( identityService == null) {
67              identityService = KimApiServiceLocator.getIdentityService();
68          }
69          return identityService;
70      }
71  
72      @Override
73      protected boolean processCustomSaveDocumentBusinessRules(Document document) {
74          if (!(document instanceof IdentityManagementGroupDocument)) {
75              return false;
76          }
77  
78          IdentityManagementGroupDocument groupDoc = (IdentityManagementGroupDocument)document;
79  
80          boolean valid = true;
81          GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
82          valid &= validAssignGroup(groupDoc);
83          valid &= validDuplicateGroupName(groupDoc);
84          getDictionaryValidationService().validateDocumentAndUpdatableReferencesRecursively(document, getMaxDictionaryValidationDepth(), true, false);
85          valid &= validateGroupQualifier(groupDoc.getQualifiers(), groupDoc.getKimType());
86          valid &= validGroupMemberActiveDates(groupDoc.getMembers());
87          //KULRICE-6858 Validate group members are in identity system
88          valid &= validGroupMemberPrincipalIDs(groupDoc.getMembers());
89          GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
90  
91          return valid;
92      }
93      
94  	protected boolean validAssignGroup(IdentityManagementGroupDocument document){
95          boolean rulePassed = true;
96          Map<String,String> additionalPermissionDetails = new HashMap<String,String>();
97          additionalPermissionDetails.put(KimConstants.AttributeConstants.NAMESPACE_CODE, document.getGroupNamespace());
98          additionalPermissionDetails.put(KimConstants.AttributeConstants.GROUP_NAME, document.getGroupName());
99  		if(document.getMembers()!=null && document.getMembers().size()>0){
100 			if(!getDocumentDictionaryService().getDocumentAuthorizer(document).isAuthorizedByTemplate(
101 					document, KimConstants.NAMESPACE_CODE, KimConstants.PermissionTemplateNames.POPULATE_GROUP,
102 					GlobalVariables.getUserSession().getPrincipalId(), additionalPermissionDetails, null)){
103 	    		GlobalVariables.getMessageMap().putError("document.groupName", 
104 	    				RiceKeyConstants.ERROR_ASSIGN_GROUP, 
105 	    				new String[] {document.getGroupNamespace(), document.getGroupName()});
106 	            rulePassed = false;
107 			}
108 		}
109 		return rulePassed;
110 	}
111 
112     @SuppressWarnings("unchecked")
113 	protected boolean validDuplicateGroupName(IdentityManagementGroupDocument groupDoc){
114         Group group = null;
115         if(null != groupDoc.getGroupNamespace() && null != groupDoc.getGroupName()){
116             group = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(
117                 groupDoc.getGroupNamespace(), groupDoc.getGroupName());
118         }
119         boolean rulePassed = true;
120     	if(group!=null){
121     		if(group.getId().equals(groupDoc.getGroupId())) {
122     			rulePassed = true;
123             }
124     		else{
125 	    		GlobalVariables.getMessageMap().putError("document.groupName", 
126 	    				RiceKeyConstants.ERROR_DUPLICATE_ENTRY, new String[] {"Group Name"});
127 	    		rulePassed = false;
128     		}
129     	}
130     	return rulePassed;
131     }
132     
133     protected boolean validGroupMemberActiveDates(List<GroupDocumentMember> groupMembers) {
134     	boolean valid = true;
135 		int i = 0;
136     	for(GroupDocumentMember groupMember: groupMembers) {
137    			valid &= validateActiveDate("document.members["+i+"].activeToDate", groupMember.getActiveFromDate(), groupMember.getActiveToDate());
138     		i++;
139     	}
140     	return valid;
141     }
142 
143     protected boolean validGroupMemberPrincipalIDs(List<GroupDocumentMember> groupMembers) {
144         boolean valid = true;
145         List<String> principalIds = new ArrayList<String>();
146         for(GroupDocumentMember groupMember: groupMembers) {
147             if (StringUtils.equals(groupMember.getMemberTypeCode(), KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode()) ) {
148                 principalIds.add(groupMember.getMemberId());
149             }
150         }
151         if(!principalIds.isEmpty())       {
152             // retrieve valid principals/principal-ids from identity service
153             List<Principal> validPrincipals = getIdentityService().getPrincipals(principalIds);
154             List<String> validPrincipalIds = new ArrayList<String>();
155             for (Principal principal : validPrincipals) {
156                 validPrincipalIds.add(principal.getPrincipalId());
157             }
158             // check that there are no invalid principals in the principal list, return false
159             List<String> invalidPrincipalIds = new ArrayList<String>(CollectionUtils.subtract(principalIds, validPrincipalIds));
160             // if list is not empty add error messages and return false
161             if(CollectionUtils.isNotEmpty(invalidPrincipalIds)) {
162                 GlobalVariables.getMessageMap().putError("document.member.memberId", RiceKeyConstants.ERROR_MEMBERID_MEMBERTYPE_MISMATCH,
163                         invalidPrincipalIds.toArray(new String[invalidPrincipalIds.size()]));
164                 valid = false;
165             }
166         }
167         return valid;
168     }
169 
170     protected boolean validateGroupQualifier(List<GroupDocumentQualifier> groupQualifiers, KimType kimType){
171 		List<RemotableAttributeError> validationErrors = new ArrayList<RemotableAttributeError>();
172 
173 		List<RemotableAttributeError> errorsTemp;
174 		Map<String, String> mapToValidate;
175         KimTypeService kimTypeService = KimFrameworkServiceLocator.getKimTypeService(kimType);
176         GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
177 		mapToValidate = attributeValidationHelper.convertQualifiersToMap(groupQualifiers);
178 		errorsTemp = kimTypeService.validateAttributes(kimType.getId(), mapToValidate);
179 		validationErrors.addAll(attributeValidationHelper.convertErrors("",
180                 attributeValidationHelper.convertQualifiersToAttrIdxMap(groupQualifiers), errorsTemp));
181 		GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME);
182 		
183     	if (validationErrors.isEmpty()) {
184     		return true;
185     	} 
186     	attributeValidationHelper.moveValidationErrorsToErrorMap(validationErrors);
187     	return false;
188     }
189     
190 	protected boolean validateActiveDate(String errorPath, Timestamp activeFromDate, Timestamp activeToDate) {
191 		// TODO : do not have detail bus rule yet, so just check this for now.
192 		boolean valid = true;
193 		if (activeFromDate != null && activeToDate !=null && activeToDate.before(activeFromDate)) {
194 	        MessageMap errorMap = GlobalVariables.getMessageMap();
195             errorMap.putError(errorPath, RiceKeyConstants.ERROR_ACTIVE_TO_DATE_BEFORE_FROM_DATE);
196             valid = false;
197 			
198 		}
199 		return valid;
200 	}
201 	
202 	/**
203 	 * @return the addGroupMemberRule
204 	 */
205 	public AddGroupMemberRule getAddGroupMemberRule() {
206 		if(addGroupMemberRule == null){
207 			try {
208 				addGroupMemberRule = addGroupMemberRuleClass.newInstance();
209 			} catch ( Exception ex ) {
210 				throw new RuntimeException( "Unable to create AddMemberRule instance using class: " + addGroupMemberRuleClass, ex );
211 			}
212 		}
213 		return addGroupMemberRule;
214 	}
215 
216     public boolean processAddGroupMember(AddGroupMemberEvent addGroupMemberEvent) {
217         return new GroupDocumentMemberRule().processAddGroupMember(addGroupMemberEvent);    
218     }
219 
220     /**
221 	 * @return the businessObjectService
222 	 */
223 	public BusinessObjectService getBusinessObjectService() {
224 		if(businessObjectService == null){
225 			businessObjectService = KRADServiceLocator.getBusinessObjectService();
226 		}
227 		return businessObjectService;
228 	}
229 
230 }