Coverage Report - org.kuali.rice.kns.dao.impl.LookupDaoJpa
 
Classes in this File Line Coverage Branch Coverage Complexity
LookupDaoJpa
0%
0/349
0%
0/222
5.621
 
 1  
 /*
 2  
  * Copyright 2005-2008 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.kns.dao.impl;
 17  
 
 18  
 import java.lang.reflect.Field;
 19  
 import java.math.BigDecimal;
 20  
 import java.sql.Timestamp;
 21  
 import java.text.ParseException;
 22  
 import java.util.ArrayList;
 23  
 import java.util.Collection;
 24  
 import java.util.Iterator;
 25  
 import java.util.List;
 26  
 import java.util.Map;
 27  
 
 28  
 import javax.persistence.EntityManager;
 29  
 import javax.persistence.PersistenceContext;
 30  
 import javax.persistence.PersistenceException;
 31  
 
 32  
 import org.apache.commons.beanutils.PropertyUtils;
 33  
 import org.apache.commons.lang.StringUtils;
 34  
 import org.kuali.rice.core.api.datetime.DateTimeService;
 35  
 import org.kuali.rice.core.framework.persistence.jpa.criteria.Criteria;
 36  
 import org.kuali.rice.core.framework.persistence.jpa.criteria.QueryByCriteria;
 37  
 import org.kuali.rice.core.framework.persistence.jpa.metadata.EntityDescriptor;
 38  
 import org.kuali.rice.core.framework.persistence.jpa.metadata.FieldDescriptor;
 39  
 import org.kuali.rice.core.framework.persistence.jpa.metadata.MetadataManager;
 40  
 import org.kuali.rice.core.framework.persistence.ojb.conversion.OjbCharBooleanConversion;
 41  
 import org.kuali.rice.core.util.RiceKeyConstants;
 42  
 import org.kuali.rice.core.util.type.TypeUtils;
 43  
 import org.kuali.rice.kns.bo.InactivateableFromTo;
 44  
 import org.kuali.rice.kns.bo.PersistableBusinessObject;
 45  
 import org.kuali.rice.kns.bo.PersistableBusinessObjectExtension;
 46  
 import org.kuali.rice.kns.dao.LookupDao;
 47  
 import org.kuali.rice.kns.lookup.CollectionIncomplete;
 48  
 import org.kuali.rice.kns.lookup.LookupUtils;
 49  
 import org.kuali.rice.kns.service.BusinessObjectDictionaryService;
 50  
 import org.kuali.rice.kns.service.KNSServiceLocatorInternal;
 51  
 import org.kuali.rice.kns.service.KNSServiceLocatorWeb;
 52  
 import org.kuali.rice.kns.service.PersistenceStructureService;
 53  
 import org.kuali.rice.kns.util.GlobalVariables;
 54  
 import org.kuali.rice.kns.util.KNSConstants;
 55  
 import org.kuali.rice.kns.util.KNSPropertyConstants;
 56  
 import org.kuali.rice.kns.util.ObjectUtils;
 57  
 import org.springframework.dao.DataIntegrityViolationException;
 58  
 
 59  
 /**
 60  
  * This class is the JPA implementation of the LookupDao interface.
 61  
  */
 62  0
 public class LookupDaoJpa implements LookupDao {
 63  0
         private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(LookupDao.class);
 64  
 
 65  
         private DateTimeService dateTimeService;
 66  
         private PersistenceStructureService persistenceStructureService;
 67  
         private BusinessObjectDictionaryService businessObjectDictionaryService;
 68  
 
 69  
         @PersistenceContext
 70  
         private EntityManager entityManager;
 71  
 
 72  
     public Long findCountByMap(Object example, Map formProps) {
 73  0
                 Criteria criteria = new Criteria(example.getClass().getName());
 74  
 
 75  
                 // iterate through the parameter map for key values search criteria
 76  0
                 Iterator propsIter = formProps.keySet().iterator();
 77  0
                 while (propsIter.hasNext()) {
 78  0
                         String propertyName = (String) propsIter.next();
 79  0
                         String searchValue = (String) formProps.get(propertyName);
 80  
 
 81  
                         // if searchValue is empty and the key is not a valid property ignore
 82  0
                         if (StringUtils.isBlank(searchValue) || !(PropertyUtils.isWriteable(example, propertyName))) {
 83  0
                                 continue;
 84  
                         }
 85  
 
 86  
                         // get property type which is used to determine type of criteria
 87  0
                         Class propertyType = ObjectUtils.getPropertyType(example, propertyName, persistenceStructureService);
 88  0
                         if (propertyType == null) {
 89  0
                                 continue;
 90  
                         }
 91  0
                         Boolean caseInsensitive = Boolean.TRUE;
 92  0
                         if (KNSServiceLocatorWeb.getDataDictionaryService().isAttributeDefined(example.getClass(), propertyName)) {
 93  0
                                 caseInsensitive = !KNSServiceLocatorWeb.getDataDictionaryService().getAttributeForceUppercase(example.getClass(), propertyName);
 94  
                         }
 95  0
                         if (caseInsensitive == null) {
 96  0
                                 caseInsensitive = Boolean.TRUE;
 97  
                         }
 98  
 
 99  0
                         boolean treatWildcardsAndOperatorsAsLiteral = KNSServiceLocatorWeb.
 100  
                                         getBusinessObjectDictionaryService().isLookupFieldTreatWildcardsAndOperatorsAsLiteral(example.getClass(), propertyName); 
 101  
                         // build criteria
 102  0
                         addCriteria(propertyName, searchValue, propertyType, caseInsensitive, treatWildcardsAndOperatorsAsLiteral, criteria);
 103  0
                 }
 104  
 
 105  
                 // execute query and return result list
 106  0
                 return (Long) new QueryByCriteria(entityManager, criteria).toCountQuery().getSingleResult();
 107  
         }
 108  
 
 109  
         public Collection findCollectionBySearchHelper(Class businessObjectClass, Map formProps, boolean unbounded, boolean usePrimaryKeyValuesOnly) {
 110  0
                 return findCollectionBySearchHelper(businessObjectClass, formProps, unbounded, usePrimaryKeyValuesOnly, null);
 111  
         }
 112  
 
 113  
         public Collection findCollectionBySearchHelper(Class businessObjectClass, Map formProps, boolean unbounded, boolean usePrimaryKeyValuesOnly, Object additionalCriteria) {
 114  0
                 PersistableBusinessObject businessObject = checkBusinessObjectClass(businessObjectClass);
 115  0
                 if (usePrimaryKeyValuesOnly) {
 116  0
                         return executeSearch(businessObjectClass, getCollectionCriteriaFromMapUsingPrimaryKeysOnly(businessObjectClass, formProps), unbounded);
 117  
                 } else {
 118  0
                         Criteria crit = getCollectionCriteriaFromMap(businessObject, formProps);
 119  0
                         if (additionalCriteria != null && additionalCriteria instanceof Criteria) {
 120  0
                                 crit.and((Criteria) additionalCriteria);
 121  
                         }
 122  0
                         return executeSearch(businessObjectClass, crit, unbounded);
 123  
                 }
 124  
         }
 125  
 
 126  
         public Criteria getCollectionCriteriaFromMap(PersistableBusinessObject example, Map formProps) {
 127  0
                 Criteria criteria = new Criteria(example.getClass().getName());
 128  0
                 Iterator propsIter = formProps.keySet().iterator();
 129  0
                 while (propsIter.hasNext()) {
 130  0
                         String propertyName = (String) propsIter.next();
 131  0
                         Boolean caseInsensitive = Boolean.TRUE;
 132  0
                         if (KNSServiceLocatorWeb.getDataDictionaryService().isAttributeDefined(example.getClass(), propertyName)) {
 133  0
                                 caseInsensitive = !KNSServiceLocatorWeb.getDataDictionaryService().getAttributeForceUppercase(example.getClass(), propertyName);
 134  
                         }
 135  0
                         if (caseInsensitive == null) {
 136  0
                                 caseInsensitive = Boolean.TRUE;
 137  
                         }
 138  0
             boolean treatWildcardsAndOperatorsAsLiteral = KNSServiceLocatorWeb.
 139  
                                     getBusinessObjectDictionaryService().isLookupFieldTreatWildcardsAndOperatorsAsLiteral(example.getClass(), propertyName);
 140  0
                         if (formProps.get(propertyName) instanceof Collection) {
 141  0
                                 Iterator iter = ((Collection) formProps.get(propertyName)).iterator();
 142  0
                                 while (iter.hasNext()) {
 143  0
                                         if (!createCriteria(example, (String) iter.next(), propertyName, caseInsensitive, treatWildcardsAndOperatorsAsLiteral, criteria, formProps)) {
 144  0
                                                 throw new RuntimeException("Invalid value in Collection");
 145  
                                         }
 146  
                                 }
 147  0
                         } else {
 148  0
                                 if (!createCriteria(example, (String) formProps.get(propertyName), propertyName, caseInsensitive, treatWildcardsAndOperatorsAsLiteral, criteria, formProps)) {
 149  0
                                         continue;
 150  
                                 }
 151  
                         }
 152  0
                 }
 153  0
                 return criteria;
 154  
         }
 155  
 
 156  
         public Criteria getCollectionCriteriaFromMapUsingPrimaryKeysOnly(Class businessObjectClass, Map formProps) {
 157  0
                 PersistableBusinessObject businessObject = checkBusinessObjectClass(businessObjectClass);
 158  0
                 Criteria criteria = new Criteria(businessObjectClass.getName());
 159  0
                 List pkFields = persistenceStructureService.listPrimaryKeyFieldNames(businessObjectClass);
 160  0
                 Iterator pkIter = pkFields.iterator();
 161  0
                 while (pkIter.hasNext()) {
 162  0
                         String pkFieldName = (String) pkIter.next();
 163  0
                         String pkValue = (String) formProps.get(pkFieldName);
 164  
 
 165  0
                         if (StringUtils.isBlank(pkValue)) {
 166  0
                                 throw new RuntimeException("Missing pk value for field " + pkFieldName + " when a search based on PK values only is performed.");
 167  0
                         } else if (StringUtils.indexOfAny(pkValue, KNSConstants.QUERY_CHARACTERS) != -1) {
 168  0
                                 throw new RuntimeException("Value \"" + pkValue + "\" for PK field " + pkFieldName + " contains wildcard/operator characters.");
 169  
                         }
 170  0
             boolean treatWildcardsAndOperatorsAsLiteral = KNSServiceLocatorWeb.
 171  
                                     getBusinessObjectDictionaryService().isLookupFieldTreatWildcardsAndOperatorsAsLiteral(businessObjectClass, pkFieldName);
 172  0
                         createCriteria(businessObject, pkValue, pkFieldName, false, treatWildcardsAndOperatorsAsLiteral, criteria);
 173  0
                 }
 174  0
                 return criteria;
 175  
         }
 176  
 
 177  
         private PersistableBusinessObject checkBusinessObjectClass(Class businessObjectClass) {
 178  0
                 if (businessObjectClass == null) {
 179  0
                         throw new IllegalArgumentException("BusinessObject class passed to LookupDao findCollectionBySearchHelper... method was null");
 180  
                 }
 181  0
                 PersistableBusinessObject businessObject = null;
 182  
                 try {
 183  0
                         businessObject = (PersistableBusinessObject) businessObjectClass.newInstance();
 184  0
                 } catch (IllegalAccessException e) {
 185  0
                         throw new RuntimeException("LookupDao could not get instance of " + businessObjectClass.getName(), e);
 186  0
                 } catch (InstantiationException e) {
 187  0
                         throw new RuntimeException("LookupDao could not get instance of " + businessObjectClass.getName(), e);
 188  0
                 }
 189  0
                 return businessObject;
 190  
         }
 191  
 
 192  
         private Collection executeSearch(Class businessObjectClass, Criteria criteria, boolean unbounded) {
 193  0
                 Collection<PersistableBusinessObject> searchResults = new ArrayList<PersistableBusinessObject>();
 194  0
                 Long matchingResultsCount = null;
 195  
                 try {
 196  0
                         Integer searchResultsLimit = LookupUtils.getSearchResultsLimit(businessObjectClass);
 197  0
                         if (!unbounded && (searchResultsLimit != null)) {
 198  0
                                 matchingResultsCount = (Long) new QueryByCriteria(entityManager, criteria).toCountQuery().getSingleResult();
 199  0
                                 searchResults = new QueryByCriteria(entityManager, criteria).toQuery().setMaxResults(searchResultsLimit).getResultList();
 200  
                         } else {
 201  0
                                 searchResults = new QueryByCriteria(entityManager, criteria).toQuery().getResultList();
 202  
                         }
 203  0
                         if ((matchingResultsCount == null) || (matchingResultsCount.intValue() <= searchResultsLimit.intValue())) {
 204  0
                                 matchingResultsCount = new Long(0);
 205  
                         }
 206  
                         // Temp solution for loading extension objects - need to find a
 207  
                         // better way
 208  
                         // Should look for a JOIN query, for the above query, that will grab
 209  
                         // the PBOEs as well (1+n query problem)
 210  0
                         for (PersistableBusinessObject bo : searchResults) {
 211  0
                                 if (bo.getExtension() != null) {
 212  0
                                         PersistableBusinessObjectExtension boe = bo.getExtension();
 213  0
                                         EntityDescriptor entity = MetadataManager.getEntityDescriptor(bo.getExtension().getClass());
 214  0
                                         Criteria extensionCriteria = new Criteria(boe.getClass().getName());
 215  0
                                         for (FieldDescriptor fieldDescriptor : entity.getPrimaryKeys()) {
 216  
                                                 try {
 217  0
                                                         Field field = bo.getClass().getDeclaredField(fieldDescriptor.getName());
 218  0
                                                         field.setAccessible(true);
 219  0
                                                         extensionCriteria.eq(fieldDescriptor.getName(), field.get(bo));
 220  0
                                                 } catch (Exception e) {
 221  0
                                                         LOG.error(e.getMessage(), e);
 222  0
                                                 }
 223  
                                         }
 224  
                                         try {
 225  0
                                                 boe = (PersistableBusinessObjectExtension) new QueryByCriteria(entityManager, extensionCriteria).toQuery().getSingleResult();
 226  0
                                         } catch (PersistenceException e) {}
 227  0
                                         bo.setExtension(boe);
 228  0
                                 }
 229  
                         }
 230  
                         // populate Person objects in business objects
 231  0
                         List bos = new ArrayList();
 232  0
                         bos.addAll(searchResults);
 233  0
                         searchResults = bos;
 234  0
                 } catch (DataIntegrityViolationException e) {
 235  0
                         throw new RuntimeException("LookupDao encountered exception during executeSearch", e);
 236  0
                 }
 237  0
                 return new CollectionIncomplete(searchResults, matchingResultsCount);
 238  
         }
 239  
 
 240  
         /**
 241  
          * Return whether or not an attribute is writeable. This method is aware
 242  
          * that that Collections may be involved and handles them consistently with
 243  
          * the way in which OJB handles specifying the attributes of elements of a
 244  
          * Collection.
 245  
          * 
 246  
          * @param o
 247  
          * @param p
 248  
          * @return
 249  
          * @throws IllegalArgumentException
 250  
          */
 251  
         private boolean isWriteable(Object o, String p) throws IllegalArgumentException {
 252  0
                 if (null == o || null == p) {
 253  0
                         throw new IllegalArgumentException("Cannot check writeable status with null arguments.");
 254  
                 }
 255  
 
 256  0
                 boolean b = false;
 257  
 
 258  
                 // Try the easy way.
 259  0
                 if (!(PropertyUtils.isWriteable(o, p))) {
 260  
 
 261  
                         // If that fails lets try to be a bit smarter, understanding that
 262  
                         // Collections may be involved.
 263  0
                         if (-1 != p.indexOf('.')) {
 264  
 
 265  0
                                 String[] parts = p.split("\\.");
 266  
 
 267  
                                 // Get the type of the attribute.
 268  0
                                 Class c = ObjectUtils.getPropertyType(o, parts[0], persistenceStructureService);
 269  
 
 270  0
                                 Object i = null;
 271  
 
 272  
                                 // If the next level is a Collection, look into the collection,
 273  
                                 // to find out what type its elements are.
 274  0
                                 if (Collection.class.isAssignableFrom(c)) {
 275  0
                                         Map<String, Class> m = persistenceStructureService.listCollectionObjectTypes(o.getClass());
 276  0
                                         c = m.get(parts[0]);
 277  
                                 }
 278  
 
 279  
                                 // Look into the attribute class to see if it is writeable.
 280  
                                 try {
 281  0
                                         i = c.newInstance();
 282  0
                                         StringBuffer sb = new StringBuffer();
 283  0
                                         for (int x = 1; x < parts.length; x++) {
 284  0
                                                 sb.append(1 == x ? "" : ".").append(parts[x]);
 285  
                                         }
 286  0
                                         b = isWriteable(i, sb.toString());
 287  0
                                 } catch (InstantiationException ie) {
 288  0
                                         LOG.info(ie);
 289  0
                                 } catch (IllegalAccessException iae) {
 290  0
                                         LOG.info(iae);
 291  0
                                 }
 292  0
                         }
 293  
                 } else {
 294  0
                         b = true;
 295  
                 }
 296  
 
 297  0
                 return b;
 298  
         }
 299  
 
 300  
         public boolean createCriteria(Object example, String searchValue, String propertyName, Object criteria) {
 301  0
                 return createCriteria(example, searchValue, propertyName, false, false, criteria);
 302  
         }
 303  
         
 304  
     public boolean createCriteria(Object example, String searchValue, String propertyName, boolean caseInsensitive, boolean treatWildcardsAndOperatorsAsLiteral, Object criteria) {
 305  0
             return createCriteria( example, searchValue, propertyName, false, false, criteria, null );
 306  
     }
 307  
 
 308  
         public boolean createCriteria(Object example, String searchValue, String propertyName, boolean caseInsensitive, boolean treatWildcardsAndOperatorsAsLiteral, Object criteria, Map searchValues) {
 309  
                 // if searchValue is empty and the key is not a valid property ignore
 310  0
                 if (!(criteria instanceof Criteria) || StringUtils.isBlank(searchValue) || !isWriteable(example, propertyName)) {
 311  0
                         return false;
 312  
                 }
 313  
 
 314  
                 // get property type which is used to determine type of criteria
 315  0
                 Class propertyType = ObjectUtils.getPropertyType(example, propertyName, persistenceStructureService);
 316  0
                 if (propertyType == null) {
 317  0
                         return false;
 318  
                 }
 319  
 
 320  
                 // build criteria
 321  0
                 if (example instanceof InactivateableFromTo) {
 322  0
                         if (KNSPropertyConstants.ACTIVE.equals(propertyName)) {
 323  0
                                 addInactivateableFromToActiveCriteria(example, searchValue, (Criteria) criteria, searchValues);
 324  0
                         } else if (KNSPropertyConstants.CURRENT.equals(propertyName)) {
 325  0
                                 addInactivateableFromToCurrentCriteria(example, searchValue, (Criteria) criteria, searchValues);
 326  0
                         } else if (!KNSPropertyConstants.ACTIVE_AS_OF_DATE.equals(propertyName)) {
 327  0
                                 addCriteria(propertyName, searchValue, propertyType, caseInsensitive,
 328  
                                                 treatWildcardsAndOperatorsAsLiteral, (Criteria) criteria);
 329  
                         }
 330  
                 } else {
 331  0
                         addCriteria(propertyName, searchValue, propertyType, caseInsensitive, treatWildcardsAndOperatorsAsLiteral,
 332  
                                         (Criteria) criteria);
 333  
                 }
 334  
                 
 335  0
                 return true;
 336  
         }
 337  
 
 338  
         /**
 339  
          * @see org.kuali.rice.kns.dao.LookupDao#findObjectByMap(java.lang.Object,
 340  
          *      java.util.Map)
 341  
          */
 342  
         public Object findObjectByMap(Object example, Map formProps) {
 343  0
                 Criteria jpaCriteria = new Criteria(example.getClass().getName());
 344  
 
 345  0
                 Iterator propsIter = formProps.keySet().iterator();
 346  0
                 while (propsIter.hasNext()) {
 347  0
                         String propertyName = (String) propsIter.next();
 348  0
                         String searchValue = "";
 349  0
                         if (formProps.get(propertyName) != null) {
 350  0
                                 searchValue = (formProps.get(propertyName)).toString();
 351  
                         }
 352  
 
 353  0
                         if (StringUtils.isNotBlank(searchValue) & PropertyUtils.isWriteable(example, propertyName)) {
 354  0
                                 Class propertyType = ObjectUtils.getPropertyType(example, propertyName, persistenceStructureService);
 355  0
                                 if (TypeUtils.isIntegralClass(propertyType) || TypeUtils.isDecimalClass(propertyType)) {
 356  0
                                         if (propertyType.equals(Long.class)) {
 357  0
                                                 jpaCriteria.eq(propertyName, new Long(searchValue));
 358  
                                         } else {
 359  0
                                                 jpaCriteria.eq(propertyName, new Integer(searchValue));
 360  
                                         }
 361  0
                                 } else if (TypeUtils.isTemporalClass(propertyType)) {
 362  0
                                         jpaCriteria.eq(propertyName, parseDate(ObjectUtils.clean(searchValue)));
 363  
                                 } else {
 364  0
                                         jpaCriteria.eq(propertyName, searchValue);
 365  
                                 }
 366  
                         }
 367  0
                 }
 368  
 
 369  0
                 return new QueryByCriteria(entityManager, jpaCriteria).toQuery().getSingleResult();
 370  
         }
 371  
 
 372  
         private void addCriteria(String propertyName, String propertyValue, Class propertyType, boolean caseInsensitive, boolean treatWildcardsAndOperatorsAsLiteral, Criteria criteria) {
 373  0
                 String alias = "";
 374  0
                 String[] keySplit = propertyName.split("\\.");
 375  0
                 if (keySplit.length > 1) {
 376  0
                         alias = keySplit[keySplit.length-2];
 377  0
                         String variableKey = keySplit[keySplit.length-1];
 378  0
                         for (int j = 0; j < keySplit.length - 1; j++)  {
 379  0
                                 if (StringUtils.contains(keySplit[j], Criteria.JPA_ALIAS_PREFIX)) {
 380  0
                                         String tempKey = keySplit[j].substring(keySplit[j].indexOf('\'', keySplit[j].indexOf(Criteria.JPA_ALIAS_PREFIX)) + 1,
 381  
                                                         keySplit[j].lastIndexOf('\'', keySplit[j].indexOf(Criteria.JPA_ALIAS_SUFFIX)));
 382  0
                                         if (criteria.getAliasIndex(tempKey) == -1) {
 383  0
                                                 criteria.join(tempKey, tempKey, false, true);
 384  
                                         }
 385  0
                                 } else {
 386  0
                                         if (criteria.getAliasIndex(keySplit[j]) == -1) {
 387  0
                                                 criteria.join(keySplit[j], keySplit[j], false, true);
 388  
                                         }
 389  
                                 }
 390  
                         }
 391  0
                         if (!StringUtils.contains(propertyName, "__JPA_ALIAS[[")) {
 392  0
                                 propertyName = "__JPA_ALIAS[['" + alias + "']]__." + variableKey;
 393  
                         }
 394  
                 }
 395  0
                 if (!treatWildcardsAndOperatorsAsLiteral && StringUtils.contains(propertyValue, KNSConstants.OR_LOGICAL_OPERATOR)) {
 396  0
                         addOrCriteria(propertyName, propertyValue, propertyType, caseInsensitive, criteria);
 397  0
                         return;
 398  
                 }
 399  
 
 400  0
                 if (!treatWildcardsAndOperatorsAsLiteral && StringUtils.contains(propertyValue, KNSConstants.AND_LOGICAL_OPERATOR)) {
 401  0
                         addAndCriteria(propertyName, propertyValue, propertyType, caseInsensitive, criteria);
 402  0
                         return;
 403  
                 }
 404  
 
 405  0
         if (StringUtils.containsIgnoreCase(propertyValue, KNSConstants.NULL_OPERATOR)) {
 406  0
                 if (StringUtils.contains(propertyValue, KNSConstants.NOT_LOGICAL_OPERATOR)) {
 407  0
                         criteria.notNull(propertyName);
 408  
                 }
 409  
                 else {
 410  0
                         criteria.isNull(propertyName);
 411  
                 }
 412  
         }
 413  0
         else if (TypeUtils.isStringClass(propertyType)) {
 414  
                         // KULRICE-85 : made string searches case insensitive - used new
 415  
                         // DBPlatform function to force strings to upper case
 416  0
                         if (caseInsensitive) {
 417  
                                 // TODO: What to do here now that the JPA version does not extend platform aware?
 418  
                                 //propertyName = getDbPlatform().getUpperCaseFunction() + "(__JPA_ALIAS[[0]]__." + propertyName + ")";
 419  0
                                 if (StringUtils.contains(propertyName, "__JPA_ALIAS[[")) {
 420  0
                                         propertyName = "UPPER(" + propertyName + ")";
 421  
                                 } else {
 422  0
                                         propertyName = "UPPER(__JPA_ALIAS[[0]]__." + propertyName + ")";
 423  
                                 }
 424  0
                                 propertyValue = propertyValue.toUpperCase();
 425  
                         }
 426  0
                         if (!treatWildcardsAndOperatorsAsLiteral && StringUtils.contains(propertyValue,
 427  
                                         KNSConstants.NOT_LOGICAL_OPERATOR)) {
 428  0
                                 addNotCriteria(propertyName, propertyValue, propertyType,
 429  
                                                 caseInsensitive, criteria);
 430  0
             } else if (
 431  
                             !treatWildcardsAndOperatorsAsLiteral && propertyValue != null && (
 432  
                                             StringUtils.contains(propertyValue, KNSConstants.BETWEEN_OPERATOR) 
 433  
                                             || propertyValue.startsWith(">")
 434  
                                             || propertyValue.startsWith("<") ) ) {
 435  0
                                 addStringRangeCriteria(propertyName, propertyValue, criteria);
 436  
                         } else {
 437  0
                                 if (treatWildcardsAndOperatorsAsLiteral) {
 438  0
                                         propertyValue = StringUtils.replace(propertyValue, "*", "\\*");
 439  
                                 }
 440  0
                                 criteria.like(propertyName, propertyValue);
 441  
                         }
 442  0
                 } else if (TypeUtils.isIntegralClass(propertyType) || TypeUtils.isDecimalClass(propertyType)) {
 443  0
                         addNumericRangeCriteria(propertyName, propertyValue, criteria);
 444  0
                 } else if (TypeUtils.isTemporalClass(propertyType)) {
 445  0
                         addDateRangeCriteria(propertyName, propertyValue, criteria);
 446  0
                 } else if (TypeUtils.isBooleanClass(propertyType)) {
 447  0
                         String temp = ObjectUtils.clean(propertyValue);
 448  0
                         criteria.eq(propertyName, ("Y".equalsIgnoreCase(temp) || "T".equalsIgnoreCase(temp) || "1".equalsIgnoreCase(temp) || "true".equalsIgnoreCase(temp)) ? true : false);
 449  0
                 } else {
 450  0
                         LOG.error("not adding criterion for: " + propertyName + "," + propertyType + "," + propertyValue);
 451  
                 }
 452  0
         }
 453  
         
 454  
     
 455  
     /**
 456  
      * Translates criteria for active status to criteria on the active from and to fields
 457  
      * 
 458  
      * @param example - business object being queried on
 459  
      * @param activeSearchValue - value for the active search field, should convert to boolean
 460  
      * @param criteria - Criteria object being built
 461  
      * @param searchValues - Map containing all search keys and values
 462  
      */
 463  
     protected void addInactivateableFromToActiveCriteria(Object example, String activeSearchValue, Criteria criteria, Map searchValues) {
 464  0
             Timestamp activeTimestamp = LookupUtils.getActiveDateTimestampForCriteria(searchValues);
 465  
                 
 466  0
             String activeBooleanStr = (String) (new OjbCharBooleanConversion()).javaToSql(activeSearchValue);
 467  0
             if (OjbCharBooleanConversion.DATABASE_BOOLEAN_TRUE_STRING_REPRESENTATION.equals(activeBooleanStr)) {
 468  
                     // (active from date <= date or active from date is null) and (date < active to date or active to date is null)
 469  0
                     Criteria criteriaBeginDate = new Criteria(example.getClass().getName());
 470  0
                     criteriaBeginDate.lte(KNSPropertyConstants.ACTIVE_FROM_DATE, activeTimestamp);
 471  
                     
 472  0
                     Criteria criteriaBeginDateNull = new Criteria(example.getClass().getName());
 473  0
                     criteriaBeginDateNull.isNull(KNSPropertyConstants.ACTIVE_FROM_DATE);
 474  0
                     criteriaBeginDate.or(criteriaBeginDateNull);
 475  
                     
 476  0
                     criteria.and(criteriaBeginDate);
 477  
                     
 478  0
                     Criteria criteriaEndDate = new Criteria(example.getClass().getName());
 479  0
                     criteriaEndDate.gt(KNSPropertyConstants.ACTIVE_TO_DATE, activeTimestamp);
 480  
             
 481  0
                     Criteria criteriaEndDateNull = new Criteria(example.getClass().getName());
 482  0
                     criteriaEndDateNull.isNull(KNSPropertyConstants.ACTIVE_TO_DATE);
 483  0
                     criteriaEndDate.or(criteriaEndDateNull);
 484  
                     
 485  0
                     criteria.and(criteriaEndDate);
 486  0
             }
 487  0
             else if (OjbCharBooleanConversion.DATABASE_BOOLEAN_FALSE_STRING_REPRESENTATION.equals(activeBooleanStr)) {
 488  
                     // (date < active from date) or (active from date is null) or (date >= active to date) 
 489  0
                     Criteria criteriaNonActive = new Criteria(example.getClass().getName());
 490  0
                     criteriaNonActive.gt(KNSPropertyConstants.ACTIVE_FROM_DATE, activeTimestamp);
 491  
                     
 492  0
                     Criteria criteriaBeginDateNull = new Criteria(example.getClass().getName());
 493  0
                     criteriaBeginDateNull.isNull(KNSPropertyConstants.ACTIVE_FROM_DATE);
 494  0
                     criteriaNonActive.or(criteriaBeginDateNull);
 495  
                     
 496  0
                     Criteria criteriaEndDate = new Criteria(example.getClass().getName());
 497  0
                     criteriaEndDate.lte(KNSPropertyConstants.ACTIVE_TO_DATE, activeTimestamp);
 498  0
                     criteriaNonActive.or(criteriaEndDate);
 499  
                     
 500  0
                     criteria.and(criteriaNonActive);
 501  
             }
 502  0
     }
 503  
     
 504  
     /**
 505  
      * Translates criteria for current status to a sub-query on active begin date
 506  
      * 
 507  
      * @param example - business object being queried on
 508  
      * @param currentSearchValue - value for the current search field, should convert to boolean
 509  
      * @param criteria - Criteria object being built
 510  
      */
 511  
         protected void addInactivateableFromToCurrentCriteria(Object example, String currentSearchValue, Criteria criteria, Map searchValues) {
 512  0
                 Timestamp activeTimestamp = LookupUtils.getActiveDateTimestampForCriteria(searchValues);
 513  
                 
 514  0
                 List<String> groupByFieldList = businessObjectDictionaryService.getGroupByAttributesForEffectiveDating(example
 515  
                                 .getClass());
 516  0
                 if (groupByFieldList == null) {
 517  0
                         return;
 518  
                 }
 519  
 
 520  0
                 String alias = "c";
 521  
 
 522  0
                 String jpql = " (select max(" + alias + "." + KNSPropertyConstants.ACTIVE_FROM_DATE + ") from "
 523  
                                 + example.getClass().getName() + " as " + alias + " where ";
 524  0
                 String activeDateDBStr = KNSServiceLocatorInternal.getDatabasePlatform().getDateSQL(dateTimeService.toDateTimeString(activeTimestamp), null);
 525  0
                 jpql += alias + "." + KNSPropertyConstants.ACTIVE_FROM_DATE + " <= '" + activeDateDBStr + "'";
 526  
 
 527  
                 // join back to main query with the group by fields
 528  0
                 boolean firstGroupBy = true;
 529  0
                 String groupByJpql = "";
 530  0
                 for (String groupByField : groupByFieldList) {
 531  0
                         if (!firstGroupBy) {
 532  0
                                 groupByJpql += ", ";
 533  
                         }
 534  
 
 535  0
                         jpql += " AND " + alias + "." + groupByField + " = " + criteria.getAlias() + "." + groupByField + " ";
 536  0
                         groupByJpql += alias + "." + groupByField;
 537  0
                         firstGroupBy = false;
 538  
                 }
 539  
 
 540  0
                 jpql += " group by " + groupByJpql + " )";
 541  
 
 542  0
                 String currentBooleanStr = (String) (new OjbCharBooleanConversion()).javaToSql(currentSearchValue);
 543  0
                 if (OjbCharBooleanConversion.DATABASE_BOOLEAN_TRUE_STRING_REPRESENTATION.equals(currentBooleanStr)) {
 544  0
                         jpql = criteria.getAlias() + "." + KNSPropertyConstants.ACTIVE_FROM_DATE + " in " + jpql;
 545  0
                 } else if (OjbCharBooleanConversion.DATABASE_BOOLEAN_FALSE_STRING_REPRESENTATION.equals(currentBooleanStr)) {
 546  0
                         jpql = criteria.getAlias() + "." + KNSPropertyConstants.ACTIVE_FROM_DATE + " not in " + jpql;
 547  
                 }
 548  
 
 549  0
                 criteria.rawJpql(jpql);
 550  0
         }
 551  
 
 552  
         private void addOrCriteria(String propertyName, String propertyValue, Class propertyType, boolean caseInsensitive, Criteria criteria) {
 553  0
                 addLogicalOperatorCriteria(propertyName, propertyValue, propertyType, caseInsensitive, criteria, KNSConstants.OR_LOGICAL_OPERATOR);
 554  0
         }
 555  
 
 556  
         private void addAndCriteria(String propertyName, String propertyValue, Class propertyType, boolean caseInsensitive, Criteria criteria) {
 557  0
                 addLogicalOperatorCriteria(propertyName, propertyValue, propertyType, caseInsensitive, criteria, KNSConstants.AND_LOGICAL_OPERATOR);
 558  0
         }
 559  
 
 560  
         private void addNotCriteria(String propertyName, String propertyValue, Class propertyType, boolean caseInsensitive, Criteria criteria) {
 561  0
                 String[] splitPropVal = StringUtils.split(propertyValue, KNSConstants.NOT_LOGICAL_OPERATOR);
 562  
 
 563  0
                 int strLength = splitPropVal.length;
 564  
                 // if more than one NOT operator assume an implicit and (i.e. !a!b = !a&!b)
 565  0
                 if (strLength > 1) {
 566  0
                         String expandedNot = "!" + StringUtils.join(splitPropVal, KNSConstants.AND_LOGICAL_OPERATOR + KNSConstants.NOT_LOGICAL_OPERATOR);
 567  
                         // we know that since this method is called, treatWildcardsAndOperatorsAsLiteral is false
 568  0
                         addCriteria(propertyName, expandedNot, propertyType, caseInsensitive, false, criteria);
 569  0
                 } else {
 570  
                         // only one so add a not like
 571  0
                         criteria.notLike(propertyName, splitPropVal[0]);
 572  
                 }
 573  0
         }
 574  
 
 575  
         private void addLogicalOperatorCriteria(String propertyName, String propertyValue, Class propertyType, boolean caseInsensitive, Criteria criteria, String splitValue) {
 576  0
                 String[] splitPropVal = StringUtils.split(propertyValue, splitValue);
 577  
 
 578  0
                 Criteria subCriteria = new Criteria("N/A");
 579  0
                 for (int i = 0; i < splitPropVal.length; i++) {
 580  0
                         Criteria predicate = new Criteria("N/A");
 581  
                         // we know that since this method is called, treatWildcardsAndOperatorsAsLiteral is false
 582  0
                         addCriteria(propertyName, splitPropVal[i], propertyType, caseInsensitive, false, predicate);
 583  0
                         if (splitValue == KNSConstants.OR_LOGICAL_OPERATOR) {
 584  0
                                 subCriteria.or(predicate);
 585  
                         }
 586  0
                         if (splitValue == KNSConstants.AND_LOGICAL_OPERATOR) {
 587  0
                                 subCriteria.and(predicate);
 588  
                         }
 589  
                 }
 590  
 
 591  0
                 criteria.and(subCriteria);
 592  0
         }
 593  
 
 594  
         private java.sql.Date parseDate(String dateString) {
 595  0
                 dateString = dateString.trim();
 596  
                 try {
 597  0
                         return dateTimeService.convertToSqlDate(dateString);
 598  0
                 } catch (ParseException ex) {
 599  0
                         return null;
 600  
                 }
 601  
         }
 602  
 
 603  
         private void addDateRangeCriteria(String propertyName, String propertyValue, Criteria criteria) {
 604  
 
 605  0
                 if (StringUtils.contains(propertyValue, KNSConstants.BETWEEN_OPERATOR)) {
 606  0
                         String[] rangeValues = StringUtils.split(propertyValue, KNSConstants.BETWEEN_OPERATOR);
 607  0
                         criteria.between(propertyName, parseDate(ObjectUtils.clean(rangeValues[0])), parseDate(ObjectUtils.clean(rangeValues[1])));
 608  0
                 } else if (propertyValue.startsWith(">=")) {
 609  0
                         criteria.gte(propertyName, parseDate(ObjectUtils.clean(propertyValue)));
 610  0
                 } else if (propertyValue.startsWith("<=")) {
 611  0
                         criteria.lte(propertyName, parseDate(ObjectUtils.clean(propertyValue)));
 612  0
                 } else if (propertyValue.startsWith(">")) {
 613  0
                         criteria.gt(propertyName, parseDate(ObjectUtils.clean(propertyValue)));
 614  0
                 } else if (propertyValue.startsWith("<")) {
 615  0
                         criteria.lt(propertyName, parseDate(ObjectUtils.clean(propertyValue)));
 616  
                 } else {
 617  0
                         criteria.eq(propertyName, parseDate(ObjectUtils.clean(propertyValue)));
 618  
                 }
 619  0
         }
 620  
 
 621  
         private BigDecimal cleanNumeric(String value) {
 622  0
                 String cleanedValue = value.replaceAll("[^-0-9.]", "");
 623  
                 // ensure only one "minus" at the beginning, if any
 624  0
                 if (cleanedValue.lastIndexOf('-') > 0) {
 625  0
                         if (cleanedValue.charAt(0) == '-') {
 626  0
                                 cleanedValue = "-" + cleanedValue.replaceAll("-", "");
 627  
                         } else {
 628  0
                                 cleanedValue = cleanedValue.replaceAll("-", "");
 629  
                         }
 630  
                 }
 631  
                 // ensure only one decimal in the string
 632  0
                 int decimalLoc = cleanedValue.lastIndexOf('.');
 633  0
                 if (cleanedValue.indexOf('.') != decimalLoc) {
 634  0
                         cleanedValue = cleanedValue.substring(0, decimalLoc).replaceAll("\\.", "") + cleanedValue.substring(decimalLoc);
 635  
                 }
 636  
                 try {
 637  0
                         return new BigDecimal(cleanedValue);
 638  0
                 } catch (NumberFormatException ex) {
 639  0
                         GlobalVariables.getMessageMap().putError(KNSConstants.DOCUMENT_ERRORS, RiceKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Numeric Input: " + value });
 640  0
                         return null;
 641  
                 }
 642  
         }
 643  
 
 644  
         private void addNumericRangeCriteria(String propertyName, String propertyValue, Criteria criteria) {
 645  
 
 646  0
                 if (StringUtils.contains(propertyValue, KNSConstants.BETWEEN_OPERATOR)) {
 647  0
                         String[] rangeValues = StringUtils.split(propertyValue, KNSConstants.BETWEEN_OPERATOR);
 648  0
                         criteria.between(propertyName, cleanNumeric(rangeValues[0]), cleanNumeric(rangeValues[1]));
 649  0
                 } else if (propertyValue.startsWith(">=")) {
 650  0
                         criteria.gte(propertyName, cleanNumeric(propertyValue));
 651  0
                 } else if (propertyValue.startsWith("<=")) {
 652  0
                         criteria.lte(propertyName, cleanNumeric(propertyValue));
 653  0
                 } else if (propertyValue.startsWith(">")) {
 654  0
                         criteria.gt(propertyName, cleanNumeric(propertyValue));
 655  0
                 } else if (propertyValue.startsWith("<")) {
 656  0
                         criteria.lt(propertyName, cleanNumeric(propertyValue));
 657  
                 } else {
 658  0
                         criteria.eq(propertyName, cleanNumeric(propertyValue));
 659  
                 }
 660  0
         }
 661  
 
 662  
         private void addStringRangeCriteria(String propertyName, String propertyValue, Criteria criteria) {
 663  
 
 664  0
                 if (StringUtils.contains(propertyValue, KNSConstants.BETWEEN_OPERATOR)) {
 665  0
                         String[] rangeValues = StringUtils.split(propertyValue, KNSConstants.BETWEEN_OPERATOR);
 666  0
                         criteria.between(propertyName, rangeValues[0], rangeValues[1]);
 667  0
                 } else if (propertyValue.startsWith(">=")) {
 668  0
                         criteria.gte(propertyName, ObjectUtils.clean(propertyValue));
 669  0
                 } else if (propertyValue.startsWith("<=")) {
 670  0
                         criteria.lte(propertyName, ObjectUtils.clean(propertyValue));
 671  0
                 } else if (propertyValue.startsWith(">")) {
 672  0
                         criteria.gt(propertyName, ObjectUtils.clean(propertyValue));
 673  0
                 } else if (propertyValue.startsWith("<")) {
 674  0
                         criteria.lt(propertyName, ObjectUtils.clean(propertyValue));
 675  
                 }
 676  0
         }
 677  
 
 678  
         /**
 679  
          * @param dateTimeService
 680  
          *            the dateTimeService to set
 681  
          */
 682  
         public void setDateTimeService(DateTimeService dateTimeService) {
 683  0
                 this.dateTimeService = dateTimeService;
 684  0
         }
 685  
 
 686  
     /**
 687  
      * @return the entityManager
 688  
      */
 689  
     public EntityManager getEntityManager() {
 690  0
         return this.entityManager;
 691  
     }
 692  
 
 693  
     /**
 694  
      * @param entityManager the entityManager to set
 695  
      */
 696  
     public void setEntityManager(EntityManager entityManager) {
 697  0
         this.entityManager = entityManager;
 698  0
     }
 699  
     
 700  
         public void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) {
 701  0
                 this.persistenceStructureService = persistenceStructureService;
 702  0
         }
 703  
 
 704  
         public void setBusinessObjectDictionaryService(BusinessObjectDictionaryService businessObjectDictionaryService) {
 705  0
                 this.businessObjectDictionaryService = businessObjectDictionaryService;
 706  0
         }
 707  
         
 708  
 }