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