View Javadoc

1   /**
2    * Copyright 2005-2012 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.impl.identity;
17  
18  import org.apache.commons.beanutils.PropertyUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.apache.log4j.Logger;
21  import org.kuali.rice.core.api.CoreApiServiceLocator;
22  import org.kuali.rice.core.api.criteria.CountFlag;
23  import org.kuali.rice.core.api.criteria.Predicate;
24  import org.kuali.rice.core.api.criteria.PredicateUtils;
25  import org.kuali.rice.core.api.criteria.QueryByCriteria;
26  import org.kuali.rice.kim.api.identity.IdentityService;
27  import org.kuali.rice.kim.api.identity.Person;
28  import org.kuali.rice.kim.api.identity.PersonService;
29  import org.kuali.rice.kim.api.identity.entity.EntityDefault;
30  import org.kuali.rice.kim.api.identity.entity.EntityDefaultQueryResults;
31  import org.kuali.rice.kim.api.identity.external.EntityExternalIdentifierType;
32  import org.kuali.rice.kim.api.identity.principal.Principal;
33  import org.kuali.rice.kim.api.identity.type.EntityTypeContactInfoDefault;
34  import org.kuali.rice.kim.api.role.RoleService;
35  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
36  import org.kuali.rice.kim.impl.KIMPropertyConstants;
37  import org.kuali.rice.kns.service.BusinessObjectMetaDataService;
38  import org.kuali.rice.kns.service.KNSServiceLocator;
39  import org.kuali.rice.kns.service.MaintenanceDocumentDictionaryService;
40  import org.kuali.rice.krad.bo.BusinessObject;
41  import org.kuali.rice.krad.bo.DataObjectRelationship;
42  import org.kuali.rice.krad.lookup.CollectionIncomplete;
43  import org.kuali.rice.krad.util.KRADConstants;
44  import org.kuali.rice.krad.util.KRADPropertyConstants;
45  import org.kuali.rice.krad.util.ObjectUtils;
46  
47  import java.security.GeneralSecurityException;
48  import java.util.ArrayList;
49  import java.util.Collection;
50  import java.util.Collections;
51  import java.util.HashMap;
52  import java.util.HashSet;
53  import java.util.Iterator;
54  import java.util.List;
55  import java.util.Map;
56  import java.util.Set;
57  
58  /**
59   * This is a description of what this class does - kellerj don't forget to fill this in. 
60   * 
61   * @author Kuali Rice Team (rice.collab@kuali.org)
62   *
63   */
64  public class PersonServiceImpl implements PersonService {
65  
66  	private static Logger LOG = Logger.getLogger( PersonServiceImpl.class );
67  	protected static final String ENTITY_EXT_ID_PROPERTY_PREFIX = "externalIdentifiers.";
68  	protected static final String ENTITY_AFFILIATION_PROPERTY_PREFIX = "affiliations.";
69  	protected static final String ENTITY_TYPE_PROPERTY_PREFIX = "entityTypeContactInfos.";
70  	protected static final String ENTITY_EMAIL_PROPERTY_PREFIX = "entityTypeContactInfos.emailAddresses.";
71  	protected static final String ENTITY_PHONE_PROPERTY_PREFIX = "entityTypeContactInfos.phoneNumbers.";
72  	protected static final String ENTITY_ADDRESS_PROPERTY_PREFIX = "entityTypeContactInfos.addresses.";
73  	protected static final String ENTITY_NAME_PROPERTY_PREFIX = "names.";
74  	protected static final String PRINCIPAL_PROPERTY_PREFIX = "principals.";
75  	protected static final String ENTITY_EMPLOYEE_ID_PROPERTY_PREFIX = "employmentInformation.";
76  	// KULRICE-4442 Special handling for extension objects
77  	protected static final String EXTENSION = "extension";
78  	
79  	private IdentityService identityService;
80  	private RoleService roleService;
81  	private BusinessObjectMetaDataService businessObjectMetaDataService;
82  	private MaintenanceDocumentDictionaryService maintenanceDocumentDictionaryService;
83  
84  	protected List<String> personEntityTypeCodes = new ArrayList<String>( 4 );
85  	// String that can be passed to the lookup framework to create an type = X OR type = Y criteria
86  	private String personEntityTypeLookupCriteria = null;
87      
88  	protected Map<String,String> baseLookupCriteria = new HashMap<String,String>();
89  	protected Map<String,String> criteriaConversion = new HashMap<String,String>();
90  	protected ArrayList<String> personCachePropertyNames = new ArrayList<String>();
91  	{
92  		// init the criteria which will need to be applied to every lookup against
93  		// the identity data tables
94  		baseLookupCriteria.put( KIMPropertyConstants.Person.ACTIVE, "Y" );
95  		baseLookupCriteria.put( ENTITY_TYPE_PROPERTY_PREFIX + KRADPropertyConstants.ACTIVE, "Y" );
96  		
97  		// create the field mappings between the Person object and the KimEntity object
98  		criteriaConversion.put( KIMPropertyConstants.Person.ENTITY_ID, KIMPropertyConstants.Entity.ID);
99  		criteriaConversion.put( KIMPropertyConstants.Person.ACTIVE, PRINCIPAL_PROPERTY_PREFIX + KRADPropertyConstants.ACTIVE );
100 		criteriaConversion.put( KIMPropertyConstants.Person.PRINCIPAL_ID, PRINCIPAL_PROPERTY_PREFIX + KIMPropertyConstants.Person.PRINCIPAL_ID );
101 		criteriaConversion.put( KIMPropertyConstants.Person.PRINCIPAL_NAME, PRINCIPAL_PROPERTY_PREFIX + KIMPropertyConstants.Person.PRINCIPAL_NAME );
102 		criteriaConversion.put( KIMPropertyConstants.Person.FIRST_NAME, "names.firstName" );
103 		criteriaConversion.put( KIMPropertyConstants.Person.LAST_NAME, "names.lastName" );
104 		criteriaConversion.put( KIMPropertyConstants.Person.MIDDLE_NAME, "names.middleName" );
105 		criteriaConversion.put( KIMPropertyConstants.Person.EMAIL_ADDRESS, "entityTypeContactInfos.emailAddresses.emailAddress" );
106 		criteriaConversion.put( KIMPropertyConstants.Person.PHONE_NUMBER, "entityTypeContactInfos.phoneNumbers.phoneNumber" );
107 		criteriaConversion.put( KIMPropertyConstants.Person.ADDRESS_LINE_1, "entityTypeContactInfos.addresses.line1" );
108 		criteriaConversion.put( KIMPropertyConstants.Person.ADDRESS_LINE_2, "entityTypeContactInfos.addresses.line2" );
109 		criteriaConversion.put( KIMPropertyConstants.Person.ADDRESS_LINE_3, "entityTypeContactInfos.addresses.line3" );
110 		criteriaConversion.put( KIMPropertyConstants.Person.CITY, "entityTypeContactInfos.addresses.city" );
111 		criteriaConversion.put( KIMPropertyConstants.Person.STATE_CODE, "entityTypeContactInfos.addresses.stateProvinceCode" );
112 		criteriaConversion.put( KIMPropertyConstants.Person.POSTAL_CODE, "entityTypeContactInfos.addresses.postalCode" );
113 		criteriaConversion.put( KIMPropertyConstants.Person.COUNTRY_CODE, "entityTypeContactInfos.addresses.countryCode" );
114 		criteriaConversion.put( KIMPropertyConstants.Person.CAMPUS_CODE, "affiliations.campusCode" );
115 		criteriaConversion.put( KIMPropertyConstants.Person.AFFILIATION_TYPE_CODE, "affiliations.affiliationTypeCode" );
116 		criteriaConversion.put( KIMPropertyConstants.Person.EXTERNAL_IDENTIFIER_TYPE_CODE, "externalIdentifiers.externalIdentifierTypeCode" );
117 		criteriaConversion.put( KIMPropertyConstants.Person.EXTERNAL_ID, "externalIdentifiers.externalId" );		
118 		criteriaConversion.put( KIMPropertyConstants.Person.EMPLOYEE_TYPE_CODE, "employmentInformation.employeeTypeCode" );
119 		criteriaConversion.put( KIMPropertyConstants.Person.EMPLOYEE_STATUS_CODE, "employmentInformation.employeeStatusCode" );
120 		criteriaConversion.put( KIMPropertyConstants.Person.EMPLOYEE_ID, "employmentInformation.employeeId" );
121 		criteriaConversion.put( KIMPropertyConstants.Person.BASE_SALARY_AMOUNT, "employmentInformation.baseSalaryAmount" );
122 		criteriaConversion.put( KIMPropertyConstants.Person.PRIMARY_DEPARTMENT_CODE, "employmentInformation.primaryDepartmentCode" );
123 
124 		personCachePropertyNames.add( KIMPropertyConstants.Person.PRINCIPAL_ID );
125 		personCachePropertyNames.add( KIMPropertyConstants.Person.PRINCIPAL_NAME );
126 		personCachePropertyNames.add( KIMPropertyConstants.Person.ENTITY_ID );
127 		personCachePropertyNames.add( KIMPropertyConstants.Person.FIRST_NAME );
128 		personCachePropertyNames.add( KIMPropertyConstants.Person.LAST_NAME );
129 		personCachePropertyNames.add( KIMPropertyConstants.Person.MIDDLE_NAME );
130 		personCachePropertyNames.add( KIMPropertyConstants.Person.CAMPUS_CODE );
131 		personCachePropertyNames.add( KIMPropertyConstants.Person.EMPLOYEE_ID );
132 		personCachePropertyNames.add( KIMPropertyConstants.Person.PRIMARY_DEPARTMENT_CODE );
133 	}
134 
135 	
136 	/**
137 	 * @see org.kuali.rice.kim.api.identity.PersonService#getPerson(java.lang.String)
138 	 */
139 	public Person getPerson(String principalId) {
140 		if ( StringUtils.isBlank(principalId) ) {
141 			return null;
142 		}
143 
144 		// get the corresponding principal
145 		final Principal principal = getIdentityService().getPrincipal( principalId );
146 		// get the identity
147 		if ( principal != null ) {
148 			final EntityDefault entity = getIdentityService().getEntityDefault(principal.getEntityId());
149          	// convert the principal and identity to a Person
150             // skip if the person was created from the DB cache
151             if (entity != null ) {
152                 return convertEntityToPerson( entity, principal );
153             }
154 		}
155 		return null;
156 	}
157 
158 	protected PersonImpl convertEntityToPerson( EntityDefault entity, Principal principal ) {
159 		try {
160 			// get the EntityEntityType for the EntityType corresponding to a Person
161 			for ( String entityTypeCode : personEntityTypeCodes ) {
162 				EntityTypeContactInfoDefault entType = entity.getEntityType( entityTypeCode );
163 				// if no "person" identity type present for the given principal, skip to the next type in the list
164 				if ( entType == null ) {
165 					continue;
166 				}
167 				// attach the principal and identity objects
168 				// PersonImpl has logic to pull the needed elements from the KimEntity-related classes
169 				return new PersonImpl( principal, entity, entityTypeCode );
170 			}
171 			return null;
172 		} catch ( Exception ex ) {
173 			// allow runtime exceptions to pass through
174 			if ( ex instanceof RuntimeException ) {
175 				throw (RuntimeException)ex;
176 			}
177 			throw new RuntimeException( "Problem building person object", ex );
178 		}
179 	}
180 	
181 	
182 	/**
183 	 * @see org.kuali.rice.kim.api.identity.PersonService#getPersonByPrincipalName(java.lang.String)
184 	 */
185 	public Person getPersonByPrincipalName(String principalName) {
186 		if ( StringUtils.isBlank(principalName) ) {
187 			return null;
188 		}
189 
190 		// get the corresponding principal
191 		final Principal principal = getIdentityService().getPrincipalByPrincipalName( principalName );
192 		// get the identity
193 		if ( principal != null ) {
194             final EntityDefault entity = getIdentityService().getEntityDefault(principal.getEntityId());
195 
196             // convert the principal and identity to a Person
197             if ( entity != null ) {
198                 return convertEntityToPerson( entity, principal );
199             }
200 		}
201 		return null;
202 	}
203 
204 	public Person getPersonByEmployeeId(String employeeId) {
205 		if ( StringUtils.isBlank( employeeId  ) ) {
206 			return null;
207 		}
208 
209 		final List<Person> people = findPeople( Collections.singletonMap(KIMPropertyConstants.Person.EMPLOYEE_ID, employeeId) );
210 		if ( !people.isEmpty() ) {
211 			return people.get(0);
212 
213 		}
214 		
215 	    // If no person was found above, check for inactive records
216         EntityDefault entity = getIdentityService().getEntityDefaultByEmployeeId(employeeId);
217         if (entity != null) {
218             if ( !entity.getPrincipals().isEmpty() ) {
219                 Principal principal = getIdentityService().getPrincipal(entity.getPrincipals().get(0).getPrincipalId());
220                 if (principal != null) {
221                     return convertEntityToPerson( entity, principal );
222                 }  
223             }
224         }
225 
226 		return null;
227 	}
228 	
229 	/**
230 	 * @see org.kuali.rice.kim.api.identity.PersonService#findPeople(Map)
231 	 */
232 	public List<Person> findPeople(Map<String, String> criteria) {
233 		return findPeople(criteria, true);
234 	}
235 	
236 	/**
237 	 * @see org.kuali.rice.kim.api.identity.PersonService#findPeople(java.util.Map, boolean)
238 	 */
239 	public List<Person> findPeople(Map<String, String> criteria, boolean unbounded) {
240 		List<Person> people = null;
241 		// protect from NPEs
242 		if ( criteria == null ) {
243 			criteria = Collections.emptyMap();
244 		}
245 		// make a copy so it can be modified safely in this method
246 		criteria = new HashMap<String, String>( criteria );
247 		
248 		// extract the role lookup parameters and then remove them since later code will not know what to do with them
249 		String roleName = criteria.get( "lookupRoleName" );
250 		String namespaceCode = criteria.get( "lookupRoleNamespaceCode" );
251 		criteria.remove("lookupRoleName");
252 		criteria.remove("lookupRoleNamespaceCode");
253 		if ( StringUtils.isNotBlank(namespaceCode) && StringUtils.isNotBlank(roleName) ) {
254 			Integer searchResultsLimit = org.kuali.rice.kns.lookup.LookupUtils.getSearchResultsLimit(PersonImpl.class);
255 			int searchResultsLimitInt = Integer.MAX_VALUE;
256 			if (searchResultsLimit != null) {
257 				searchResultsLimitInt = searchResultsLimit.intValue();
258 			}
259 			if ( LOG.isDebugEnabled() ) {
260 				LOG.debug("Performing Person search including role filter: " + namespaceCode + "/" + roleName );
261 			}
262 			if ( criteria.size() == 1 && criteria.containsKey(KIMPropertyConstants.Person.ACTIVE) ) { // if only active is specified
263 				if ( LOG.isDebugEnabled() ) {
264 					LOG.debug( "Only active criteria specified, running role search first" );
265 				}
266 				// in this case, run the role lookup first and pass those results to the person lookup
267 				Collection<String> principalIds = getRoleService().getRoleMemberPrincipalIds(namespaceCode, roleName,  Collections.<String, String>emptyMap());
268 				StringBuffer sb = new StringBuffer(principalIds.size()*15);
269 				Iterator<String> pi = principalIds.iterator();
270 				while ( pi.hasNext() ) {
271 					sb.append( pi.next() );
272 					if ( pi.hasNext() ) sb.append( '|' );
273 				}
274 				// add the list of principal IDs to the lookup so that only matching Person objects are returned
275 				criteria.put( KIMPropertyConstants.Person.PRINCIPAL_ID, sb.toString() );
276 				people = findPeopleInternal(criteria, false); // can allow internal method to filter here since no more filtering necessary				
277 			} else if ( !criteria.isEmpty() ) { // i.e., person criteria are specified
278 				if ( LOG.isDebugEnabled() ) {
279 					LOG.debug( "Person criteria also specified, running that search first" );
280 				}
281 				// run the person lookup first
282 				people = findPeopleInternal(criteria, true); // get all, since may need to be filtered
283 				// TODO - now check if these people have the given role
284 				// build a principal list
285 				List<String> principalIds = peopleToPrincipalIds( people );
286 				// get sublist of principals that have the given roles
287 				principalIds = getRoleService().getPrincipalIdSubListWithRole(principalIds, namespaceCode, roleName,  Collections.<String, String>emptyMap());
288 				// re-convert into people objects, wrapping in CollectionIncomplete if needed
289 				if ( !unbounded && principalIds.size() > searchResultsLimitInt ) {
290 					int actualResultSize = principalIds.size();
291 					// trim the list down before converting to people
292 					principalIds = new ArrayList<String>(principalIds).subList(0, searchResultsLimitInt); // yes, this is a little wasteful
293 					people = getPeople(principalIds); // convert the results to people
294 					people = new CollectionIncomplete<Person>( people.subList(0, searchResultsLimitInt), new Long(actualResultSize) );
295 				} else {
296 					people = getPeople(principalIds);
297 				}
298 			} else { // only role criteria specified
299 				if ( LOG.isDebugEnabled() ) {
300 					LOG.debug( "No Person criteria specified - only using role service." );
301 				}
302 				// run the role criteria to get the principals with the role
303 				Collection<String> principalIds = getRoleService().getRoleMemberPrincipalIds(namespaceCode, roleName,  Collections.<String, String>emptyMap());
304 				if ( !unbounded && principalIds.size() > searchResultsLimitInt ) {
305 					int actualResultSize = principalIds.size();
306 					// trim the list down before converting to people
307 					principalIds = new ArrayList<String>(principalIds).subList(0, searchResultsLimitInt); // yes, this is a little wasteful
308 					people = getPeople(principalIds); // convert the results to people
309 					people = new CollectionIncomplete<Person>( people.subList(0, searchResultsLimitInt), new Long(actualResultSize) );
310 				} else {
311 					people = getPeople(principalIds); // convert the results to people
312 				}
313 			}
314 		} else {
315 			if ( LOG.isDebugEnabled() ) {
316 				LOG.debug( "No Role criteria specified, running person lookup as normal." );
317 			}
318 			people = findPeopleInternal(criteria, unbounded);
319 		}
320 			
321 		// The following change is for KULRICE-5694 - It prevents duplicate rows from being returned for the 
322 		// person inquiry (In this case, duplicate meaning same entityId, principalId, and principalNm).  
323 		// This allows for multiple rows to be returned if an entityID has more then one principal name
324 		// or more than one principal ID.  
325         Set<String> peopleNoDupsSet = new HashSet<String>();
326         List<Person> peopleNoDupsList = new ArrayList<Person>();
327 
328 	    for (Iterator<Person> iter = people.iterator(); iter.hasNext(); ) {
329 	        Person person = iter.next();
330 	        if (peopleNoDupsSet.add(person.getEntityId() + person.getPrincipalId() + person.getPrincipalName())) {
331 	            peopleNoDupsList.add(person);
332 	        }
333 	    }
334 	     
335 	    people.clear();
336 	    people.addAll(peopleNoDupsList);
337 		
338 	    return people;
339 	}
340 	
341 	@SuppressWarnings("unchecked")
342 	protected List<Person> findPeopleInternal(Map<String,String> criteria, boolean unbounded ) {
343 		// convert the criteria to a form that can be used by the ORM layer
344 
345         //TODO convert this to the new criteria predicates
346 		Map<String,String> entityCriteria = convertPersonPropertiesToEntityProperties( criteria );
347 
348         Predicate predicate = PredicateUtils.convertMapToPredicate(entityCriteria);
349 
350         QueryByCriteria.Builder queryBuilder = QueryByCriteria.Builder.create();
351         queryBuilder.setPredicates(predicate);
352         
353 		if (!unbounded) {
354 			Integer searchResultsLimit = org.kuali.rice.kns.lookup.LookupUtils.getSearchResultsLimit(PersonImpl.class);
355     		if (searchResultsLimit != null && searchResultsLimit >= 0) {
356     			queryBuilder.setMaxResults(searchResultsLimit);
357     			queryBuilder.setCountFlag(CountFlag.INCLUDE);
358 			}
359 		}
360 		
361 		List<Person> people = new ArrayList<Person>();
362 
363 		EntityDefaultQueryResults qr = getIdentityService().findEntityDefaults( queryBuilder.build() );
364 
365         if (qr.getResults().size() > 0) {
366 
367             for ( EntityDefault e : qr.getResults() ) {
368 			    // get to get all principals for the identity as well
369 			    for ( Principal p : e.getPrincipals() ) {
370 			    	people.add( convertEntityToPerson( e, p ) );
371 			    }
372 		    }
373         } else if (!qr.isMoreResultsAvailable() && entityCriteria.containsKey("principals.principalId")) {
374             if (!(entityCriteria.containsKey(KIMPropertyConstants.Person.ACTIVE)) || (criteria.get(KIMPropertyConstants.Person.ACTIVE).equals("N"))) {
375                 String principalId =  entityCriteria.get("principals.principalId");
376                 try {
377                     EntityDefault entityDefault = getIdentityService().getEntityDefaultByPrincipalId(principalId);
378                     for ( Principal p : entityDefault.getPrincipals() ) {
379                         if (!p.isActive()){
380                             people.add( convertEntityToPerson(entityDefault, p ) );
381                         }
382                     }
383                 } catch ( Exception e ) {
384                     LOG.info( "A principal Id of " + principalId + " dose not exist in the system");
385                 }
386             }
387         } else if (!qr.isMoreResultsAvailable() &&  entityCriteria.containsKey("principals.principalName")) {
388             if (!(entityCriteria.containsKey(KIMPropertyConstants.Person.ACTIVE)) || (criteria.get(KIMPropertyConstants.Person.ACTIVE).equals("N"))) {
389                 String principalNm =  entityCriteria.get("principals.principalName");
390                 try {
391                     EntityDefault entityDefault = getIdentityService().getEntityDefaultByPrincipalName(principalNm);
392                     for ( Principal p : entityDefault.getPrincipals() ) {
393                         if (!p.isActive()){
394                             people.add( convertEntityToPerson(entityDefault, p ) );
395                         }
396                     }
397                 } catch ( Exception e ) {
398                     LOG.info( "A principal name of " + principalNm + " dose not exist in the system");
399                 }
400             }
401         }
402         return people;
403 	}
404 
405 	public Map<String,String> convertPersonPropertiesToEntityProperties( Map<String,String> criteria ) {
406 		if ( LOG.isDebugEnabled() ) {
407 			LOG.debug( "convertPersonPropertiesToEntityProperties: " + criteria );
408 		}
409 		boolean nameCriteria = false;
410 		boolean addressCriteria = false;
411 		boolean externalIdentifierCriteria = false;
412 		boolean affiliationCriteria = false;
413 		boolean affiliationDefaultOnlyCriteria = false;
414 		boolean phoneCriteria = false;
415 		boolean emailCriteria = false;
416 		boolean employeeIdCriteria = false;
417 		// add base lookups for all person lookups
418 		HashMap<String,String> newCriteria = new HashMap<String,String>();
419 		newCriteria.putAll( baseLookupCriteria );
420 
421 		newCriteria.put( "entityTypeContactInfos.entityTypeCode", personEntityTypeLookupCriteria );
422 
423         if ( criteria != null ) {
424 			for ( String key : criteria.keySet() ) {
425 			    //check active radio button
426 	            if(key.equals(KIMPropertyConstants.Person.ACTIVE)) {
427 	                newCriteria.put(criteriaConversion.get(KIMPropertyConstants.Person.ACTIVE), criteria.get(KIMPropertyConstants.Person.ACTIVE));
428 	            } else {
429 	                // The following if statement enables the "both" button to work correctly.
430 	                if (!(criteria.containsKey(KIMPropertyConstants.Person.ACTIVE))) {
431 	                    newCriteria.remove( KIMPropertyConstants.Person.ACTIVE );
432 	                }
433 	            }
434 	            
435 				// if no value was passed, skip the entry in the Map
436 				if ( StringUtils.isEmpty( criteria.get(key) ) ) {
437 					continue;
438 				}
439 				// check if the value needs to be encrypted
440 				// handle encrypted external identifiers
441 				if ( key.equals( KIMPropertyConstants.Person.EXTERNAL_ID ) && StringUtils.isNotBlank(criteria.get(key)) ) {
442 					// look for a ext ID type property
443 					if ( criteria.containsKey( KIMPropertyConstants.Person.EXTERNAL_IDENTIFIER_TYPE_CODE ) ) {
444 						String extIdTypeCode = criteria.get(KIMPropertyConstants.Person.EXTERNAL_IDENTIFIER_TYPE_CODE);
445 						if ( StringUtils.isNotBlank(extIdTypeCode) ) {
446 							// if found, load that external ID Type via service
447 							EntityExternalIdentifierType extIdType = getIdentityService().getExternalIdentifierType(extIdTypeCode);
448 							// if that type needs to be encrypted, encrypt the value in the criteria map
449 							if ( extIdType != null && extIdType.isEncryptionRequired() ) {
450 								try {
451 									criteria.put(key, 
452 											CoreApiServiceLocator.getEncryptionService().encrypt(criteria.get(key))
453 											);
454 								} catch (GeneralSecurityException ex) {
455 									LOG.error("Unable to encrypt value for external ID search of type " + extIdTypeCode, ex );
456 								}								
457 							}
458 						}
459 					}
460 				}
461 				
462 				// convert the property to the Entity data model
463 				String entityProperty = criteriaConversion.get( key );
464 				if ( entityProperty != null ) {
465 					newCriteria.put( entityProperty, criteria.get( key ) );
466 				} else {
467 					entityProperty = key;
468 					// just pass it through if no translation present
469 					newCriteria.put( key, criteria.get( key ) );
470 				}
471 				// check if additional criteria are needed based on the types of properties specified
472 				if ( isNameEntityCriteria( entityProperty ) ) {
473 					nameCriteria = true;
474 				}
475 				if ( isExternalIdentifierEntityCriteria( entityProperty ) ) {
476 					externalIdentifierCriteria = true;
477 				}
478 				if ( isAffiliationEntityCriteria( entityProperty ) ) {
479 					affiliationCriteria = true;
480 				}
481 				if ( isAddressEntityCriteria( entityProperty ) ) {
482 					addressCriteria = true;
483 				}
484 				if ( isPhoneEntityCriteria( entityProperty ) ) {
485 					phoneCriteria = true;
486 				}
487 				if ( isEmailEntityCriteria( entityProperty ) ) {
488 					emailCriteria = true;
489 				}
490 				if ( isEmployeeIdEntityCriteria( entityProperty ) ) {
491 					employeeIdCriteria = true;
492 				}				
493 				// special handling for the campus code, since that forces the query to look
494 				// at the default affiliation record only
495 				if ( key.equals( "campusCode" ) ) {
496 					affiliationDefaultOnlyCriteria = true;
497 				}
498 			} 
499 			
500 			if ( nameCriteria ) {
501 				newCriteria.put( ENTITY_NAME_PROPERTY_PREFIX + "active", "Y" );
502 				newCriteria.put( ENTITY_NAME_PROPERTY_PREFIX + "defaultValue", "Y" );
503 				//newCriteria.put(ENTITY_NAME_PROPERTY_PREFIX + "nameCode", "PRFR");//so we only display 1 result
504 			}
505 			if ( addressCriteria ) {
506 				newCriteria.put( ENTITY_ADDRESS_PROPERTY_PREFIX + "active", "Y" );
507 				newCriteria.put( ENTITY_ADDRESS_PROPERTY_PREFIX + "defaultValue", "Y" );
508 			}
509 			if ( phoneCriteria ) {
510 				newCriteria.put( ENTITY_PHONE_PROPERTY_PREFIX + "active", "Y" );
511 				newCriteria.put( ENTITY_PHONE_PROPERTY_PREFIX + "defaultValue", "Y" );
512 			}
513 			if ( emailCriteria ) {
514 				newCriteria.put( ENTITY_EMAIL_PROPERTY_PREFIX + "active", "Y" );
515 				newCriteria.put( ENTITY_EMAIL_PROPERTY_PREFIX + "defaultValue", "Y" );
516 			}
517 			if ( employeeIdCriteria ) {
518 				newCriteria.put( ENTITY_EMPLOYEE_ID_PROPERTY_PREFIX + "active", "Y" );
519 				newCriteria.put( ENTITY_EMPLOYEE_ID_PROPERTY_PREFIX + "primary", "Y" );
520 			}
521 			if ( affiliationCriteria ) {
522 				newCriteria.put( ENTITY_AFFILIATION_PROPERTY_PREFIX + "active", "Y" );
523 			}
524 			if ( affiliationDefaultOnlyCriteria ) {
525 				newCriteria.put( ENTITY_AFFILIATION_PROPERTY_PREFIX + "defaultValue", "Y" );
526 			} 
527         }   
528 		
529 		if ( LOG.isDebugEnabled() ) {
530 			LOG.debug( "Converted: " + newCriteria );
531 		}
532 		return newCriteria;		
533 	}
534 
535 	protected boolean isNameEntityCriteria( String propertyName ) {
536 		return propertyName.startsWith( ENTITY_NAME_PROPERTY_PREFIX );
537 	}
538 	protected boolean isAddressEntityCriteria( String propertyName ) {
539 		return propertyName.startsWith( ENTITY_ADDRESS_PROPERTY_PREFIX );
540 	}
541 	protected boolean isPhoneEntityCriteria( String propertyName ) {
542 		return propertyName.startsWith( ENTITY_PHONE_PROPERTY_PREFIX );
543 	}
544 	protected boolean isEmailEntityCriteria( String propertyName ) {
545 		return propertyName.startsWith( ENTITY_EMAIL_PROPERTY_PREFIX );
546 	}
547 	protected boolean isEmployeeIdEntityCriteria( String propertyName ) {
548 		return propertyName.startsWith( ENTITY_EMPLOYEE_ID_PROPERTY_PREFIX );
549 	}
550 	protected boolean isAffiliationEntityCriteria( String propertyName ) {
551 		return propertyName.startsWith( ENTITY_AFFILIATION_PROPERTY_PREFIX );
552 	}
553 	protected boolean isExternalIdentifierEntityCriteria( String propertyName ) {
554 		return propertyName.startsWith( ENTITY_EXT_ID_PROPERTY_PREFIX );
555 	}
556 	
557 	/**
558 	 * Get the entityTypeCode that can be associated with a Person.  This will determine
559 	 * where EntityType-related data is pulled from within the KimEntity object.  The codes
560 	 * in the list will be examined in the order present.
561 	 */
562 	public List<String> getPersonEntityTypeCodes() {
563 		return this.personEntityTypeCodes;
564 	}
565 
566 	public void setPersonEntityTypeCodes(List<String> personEntityTypeCodes) {
567 		this.personEntityTypeCodes = personEntityTypeCodes;
568 		personEntityTypeLookupCriteria = null;
569 		for ( String entityTypeCode : personEntityTypeCodes ) {
570 			if ( personEntityTypeLookupCriteria == null ) {
571 				personEntityTypeLookupCriteria = entityTypeCode;
572 			} else {
573 				personEntityTypeLookupCriteria = personEntityTypeLookupCriteria + "|" + entityTypeCode;
574 			}
575 		}
576 	}
577 
578 	
579 	protected List<Person> getPeople( Collection<String> principalIds ) {
580 		List<Person> people = new ArrayList<Person>( principalIds.size() );
581 		for ( String principalId : principalIds ) {
582 			people.add( getPerson(principalId) );
583 		}
584 		return people;
585 	}
586 	
587 	protected List<String> peopleToPrincipalIds( List<Person> people ) {
588 		List<String> principalIds = new ArrayList<String>();
589 		
590 		for ( Person person : people ) {
591 			principalIds.add( person.getPrincipalId() );
592 		}
593 		
594 		return principalIds;
595 	}
596 	
597 	/**
598 	 * @see org.kuali.rice.kim.api.identity.PersonService#getPersonByExternalIdentifier(java.lang.String, java.lang.String)
599 	 */
600 	public List<Person> getPersonByExternalIdentifier(String externalIdentifierTypeCode, String externalId) {
601 		if (StringUtils.isBlank( externalIdentifierTypeCode ) || StringUtils.isBlank( externalId ) ) {
602 			return null;
603 		}
604 		Map<String,String> criteria = new HashMap<String,String>( 2 );
605 		criteria.put( KIMPropertyConstants.Person.EXTERNAL_IDENTIFIER_TYPE_CODE, externalIdentifierTypeCode );
606 		criteria.put( KIMPropertyConstants.Person.EXTERNAL_ID, externalId );
607 		return findPeople( criteria );
608 	}
609 	
610 	/**
611 	 * @see org.kuali.rice.kim.api.identity.PersonService#updatePersonIfNecessary(java.lang.String, org.kuali.rice.kim.api.identity.Person)
612 	 */
613     public Person updatePersonIfNecessary(String sourcePrincipalId, Person currentPerson ) {
614         if (currentPerson  == null // no person set
615                 || !StringUtils.equals(sourcePrincipalId, currentPerson.getPrincipalId() ) // principal ID mismatch
616                 || currentPerson.getEntityId() == null ) { // syntheticially created Person object
617             Person person = getPerson( sourcePrincipalId );
618             // if a synthetically created person object is present, leave it - required for property derivation and the UI layer for
619             // setting the principal name
620             if ( person == null ) {
621                 if ( currentPerson != null && currentPerson.getEntityId() == null ) {
622                     return currentPerson;
623                 }
624             }
625             // if both are null, create an empty object for property derivation
626             if ( person == null && currentPerson == null ) {
627             	try {
628             		return new PersonImpl();
629             	} catch ( Exception ex ) {
630             		LOG.error( "unable to instantiate an object of type: " + getPersonImplementationClass() + " - returning null", ex );
631             		return null;
632             	}
633             }
634             return person;
635         }
636         // otherwise, no need to change the given object
637         return currentPerson;
638     }
639 
640     /**
641      * Builds a map containing entries from the passed in Map that do NOT represent properties on an embedded
642      * Person object.
643      */
644     private Map<String,String> getNonPersonSearchCriteria( BusinessObject bo, Map<String,String> fieldValues) {
645         Map<String,String> nonUniversalUserSearchCriteria = new HashMap<String,String>();
646         for ( String propertyName : fieldValues.keySet() ) {
647             if (!isPersonProperty(bo, propertyName)) {
648                 nonUniversalUserSearchCriteria.put(propertyName, fieldValues.get(propertyName));
649             }
650         }
651         return nonUniversalUserSearchCriteria;
652     }
653 
654 
655     private boolean isPersonProperty(BusinessObject bo, String propertyName) {
656         try {
657         	if ( ObjectUtils.isNestedAttribute( propertyName ) // is a nested property
658             		&& !StringUtils.contains(propertyName, "add.") ) {// exclude add line properties (due to path parsing problems in PropertyUtils.getPropertyType)
659         		Class<?> type = PropertyUtils.getPropertyType(bo, ObjectUtils.getNestedAttributePrefix( propertyName ));
660         		// property type indicates a Person object
661         		if ( type != null ) {
662         			return Person.class.isAssignableFrom(type);
663         		}
664         		LOG.warn( "Unable to determine type of nested property: " + bo.getClass().getName() + " / " + propertyName );
665         	}
666         } catch (Exception ex) {
667         	if ( LOG.isDebugEnabled() ) {
668         		LOG.debug("Unable to determine if property on " + bo.getClass().getName() + " to a person object: " + propertyName, ex );
669         	}
670         }
671         return false;
672     }
673     
674     /**
675      * @see org.kuali.rice.kim.api.identity.PersonService#resolvePrincipalNamesToPrincipalIds(org.kuali.rice.krad.bo.BusinessObject, java.util.Map)
676      */
677     @SuppressWarnings("unchecked")
678 	public Map<String,String> resolvePrincipalNamesToPrincipalIds(BusinessObject businessObject, Map<String,String> fieldValues) {
679     	if ( fieldValues == null ) {
680     		return null;
681     	}
682     	if ( businessObject == null ) {
683     		return fieldValues;
684     	}
685     	StringBuffer resolvedPrincipalIdPropertyName = new StringBuffer();
686     	// save off all criteria which are not references to Person properties
687     	// leave person properties out so they can be resolved and replaced by this method
688         Map<String,String> processedFieldValues = getNonPersonSearchCriteria(businessObject, fieldValues);
689         for ( String propertyName : fieldValues.keySet() ) {        	
690             if (	!StringUtils.isBlank(fieldValues.get(propertyName))  // property has a value
691             		&& isPersonProperty(businessObject, propertyName) // is a property on a Person object
692             		) {
693             	// strip off the prefix on the property
694                 String personPropertyName = ObjectUtils.getNestedAttributePrimitive( propertyName );
695                 // special case - the user ID 
696                 if ( StringUtils.equals( KIMPropertyConstants.Person.PRINCIPAL_NAME, personPropertyName) ) {
697                     Class targetBusinessObjectClass = null;
698                     BusinessObject targetBusinessObject = null;
699                     resolvedPrincipalIdPropertyName.setLength( 0 ); // clear the buffer without requiring a new object allocation on each iteration
700                 	// get the property name up until the ".principalName"
701                 	// this should be a reference to the Person object attached to the BusinessObject                	
702                 	String personReferenceObjectPropertyName = ObjectUtils.getNestedAttributePrefix( propertyName );
703                 	// check if the person was nested within another BO under the master BO.  If so, go up one more level
704                 	// otherwise, use the passed in BO class as the target class
705                     if ( ObjectUtils.isNestedAttribute( personReferenceObjectPropertyName ) ) {
706                         String targetBusinessObjectPropertyName = ObjectUtils.getNestedAttributePrefix( personReferenceObjectPropertyName );
707                         targetBusinessObject = (BusinessObject)ObjectUtils.getPropertyValue( businessObject, targetBusinessObjectPropertyName );
708                         if (targetBusinessObject != null) {
709                             targetBusinessObjectClass = targetBusinessObject.getClass();
710                             resolvedPrincipalIdPropertyName.append(targetBusinessObjectPropertyName).append(".");
711                         } else {
712                             LOG.error("Could not find target property '"+propertyName+"' in class "+businessObject.getClass().getName()+". Property value was null.");
713                         }
714                     } else { // not a nested Person property
715                         targetBusinessObjectClass = businessObject.getClass();
716                         targetBusinessObject = businessObject;
717                     }
718                     
719                     if (targetBusinessObjectClass != null) {
720                     	// use the relationship metadata in the KNS to determine the property on the
721                     	// host business object to put back into the map now that the principal ID
722                     	// (the value stored in application tables) has been resolved
723                         String propName = ObjectUtils.getNestedAttributePrimitive( personReferenceObjectPropertyName );
724                         DataObjectRelationship rel = getBusinessObjectMetaDataService().getBusinessObjectRelationship( targetBusinessObject, propName );
725                         if ( rel != null ) {
726                             String sourcePrimitivePropertyName = rel.getParentAttributeForChildAttribute(KIMPropertyConstants.Person.PRINCIPAL_ID);
727                             resolvedPrincipalIdPropertyName.append(sourcePrimitivePropertyName);
728                         	// get the principal - for translation of the principalName to principalId
729                             String principalName = fieldValues.get( propertyName );
730                         	Principal principal = getIdentityService().getPrincipalByPrincipalName( principalName );
731                             if (principal != null ) {
732                                 processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), principal.getPrincipalId());
733                             } else {
734                                 processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null);
735                                 try {
736                                     // if the principalName is bad, then we need to clear out the Person object
737                                     // and base principalId property
738                                     // so that their values are no longer accidentally used or re-populate
739                                     // the object
740                                     ObjectUtils.setObjectProperty(targetBusinessObject, resolvedPrincipalIdPropertyName.toString(), null );
741                                     ObjectUtils.setObjectProperty(targetBusinessObject, propName, null );
742                                     ObjectUtils.setObjectProperty(targetBusinessObject, propName + ".principalName", principalName );
743                                 } catch ( Exception ex ) {
744                                     LOG.error( "Unable to blank out the person object after finding that the person with the given principalName does not exist.", ex );
745                                 }
746                             }
747                         } else {
748                         	LOG.error( "Missing relationship for " + propName + " on " + targetBusinessObjectClass.getName() );
749                         }
750                     } else { // no target BO class - the code below probably will not work
751                         processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null);
752                     }
753                 }
754             // if the property does not seem to match the definition of a Person property but it
755             // does end in principalName then...
756             // this is to handle the case where the user ID is on an ADD line - a case excluded from isPersonProperty()
757             } else if (propertyName.endsWith("." + KIMPropertyConstants.Person.PRINCIPAL_NAME)){
758                 // if we're adding to a collection and we've got the principalName; let's populate universalUser
759                 String principalName = fieldValues.get(propertyName);
760                 if ( StringUtils.isNotEmpty( principalName ) ) {
761                     String containerPropertyName = propertyName;
762                     if (containerPropertyName.startsWith(KRADConstants.MAINTENANCE_ADD_PREFIX)) {
763                         containerPropertyName = StringUtils.substringAfter( propertyName, KRADConstants.MAINTENANCE_ADD_PREFIX );
764                     }
765                     // get the class of the object that is referenced by the property name
766                     // if this is not true then there's a principalName collection or primitive attribute 
767                     // directly on the BO on the add line, so we just ignore that since something is wrong here
768                     if ( ObjectUtils.isNestedAttribute( containerPropertyName ) ) {
769                     	// the first part of the property is the collection name
770                         String collectionName = StringUtils.substringBefore( containerPropertyName, "." );
771                         // what is the class held by that collection?
772                         // JHK: I don't like this.  This assumes that this method is only used by the maintenance
773                         // document service.  If that will always be the case, this method should be moved over there.
774                         Class<? extends BusinessObject> collectionBusinessObjectClass = getMaintenanceDocumentDictionaryService()
775                         		.getCollectionBusinessObjectClass(
776                         				getMaintenanceDocumentDictionaryService()
777                         						.getDocumentTypeName(businessObject.getClass()), collectionName);
778                         if (collectionBusinessObjectClass != null) {
779                             // we are adding to a collection; get the relationships for that object; 
780                         	// is there one for personUniversalIdentifier?
781                             List<DataObjectRelationship> relationships =
782                             		getBusinessObjectMetaDataService().getBusinessObjectRelationships( collectionBusinessObjectClass );
783                             // JHK: this seems like a hack - looking at all relationships for a BO does not guarantee that we get the right one
784                             // JHK: why not inspect the objects like above?  Is it the property path problems because of the .add. portion?
785                             for ( DataObjectRelationship rel : relationships ) {
786                             	String parentAttribute = rel.getParentAttributeForChildAttribute( KIMPropertyConstants.Person.PRINCIPAL_ID );
787                             	if ( parentAttribute == null ) {
788                             		continue;
789                             	}
790                                 // there is a relationship for personUserIdentifier; use that to find the universal user
791                             	processedFieldValues.remove( propertyName );
792                         		String fieldPrefix = StringUtils.substringBeforeLast( StringUtils.substringBeforeLast( propertyName, "." + KIMPropertyConstants.Person.PRINCIPAL_NAME ), "." );
793                                 String relatedPrincipalIdPropertyName = fieldPrefix + "." + parentAttribute;
794                                 // KR-683 Special handling for extension objects
795                          	 	if(EXTENSION.equals(StringUtils.substringAfterLast(fieldPrefix, ".")) && EXTENSION.equals(StringUtils.substringBefore(parentAttribute, ".")))
796                          	 	{
797                          	 		relatedPrincipalIdPropertyName = fieldPrefix + "." + StringUtils.substringAfter(parentAttribute, ".");
798                          	 	}
799                                 String currRelatedPersonPrincipalId = processedFieldValues.get(relatedPrincipalIdPropertyName);
800                                 if ( StringUtils.isBlank( currRelatedPersonPrincipalId ) ) {
801                                 	Principal principal = getIdentityService().getPrincipalByPrincipalName( principalName );
802                                 	if ( principal != null ) {
803                                 		processedFieldValues.put(relatedPrincipalIdPropertyName, principal.getPrincipalId());
804                                 	} else {
805                                 		processedFieldValues.put(relatedPrincipalIdPropertyName, null);
806                                 	}
807                                 }
808                             } // relationship loop
809                         } else {
810                         	if ( LOG.isDebugEnabled() ) {
811                         		LOG.debug( "Unable to determine class for collection referenced as part of property: " + containerPropertyName + " on " + businessObject.getClass().getName() );
812                         	}
813                         }
814                     } else {
815                     	if ( LOG.isDebugEnabled() ) {
816                     		LOG.debug( "Non-nested property ending with 'principalName': " + containerPropertyName + " on " + businessObject.getClass().getName() );
817                     	}
818                     }
819                 }
820             }
821         }
822         return processedFieldValues;
823     }
824 	
825 	// OTHER METHODS
826 
827 	protected IdentityService getIdentityService() {
828 		if ( identityService == null ) {
829 			identityService = KimApiServiceLocator.getIdentityService();
830 		}
831 		return identityService;
832 	}
833 
834 	protected RoleService getRoleService() {
835 		if ( roleService == null ) {
836 			roleService = KimApiServiceLocator.getRoleService();
837 		}
838 		return roleService;
839 	}
840 
841 
842 	public Class<? extends Person> getPersonImplementationClass() {
843 		return PersonImpl.class;
844 	}
845 	
846 	protected BusinessObjectMetaDataService getBusinessObjectMetaDataService() {
847 		if ( businessObjectMetaDataService == null ) {
848 			businessObjectMetaDataService = KNSServiceLocator.getBusinessObjectMetaDataService();
849 		}
850 		return businessObjectMetaDataService;
851 	}
852 
853 	protected MaintenanceDocumentDictionaryService getMaintenanceDocumentDictionaryService() {
854 		if ( maintenanceDocumentDictionaryService == null ) {
855 			maintenanceDocumentDictionaryService = KNSServiceLocator.getMaintenanceDocumentDictionaryService();
856 		}
857 		return maintenanceDocumentDictionaryService;
858 	}
859 }