Coverage Report - org.kuali.student.r2.common.criteria.impl.CriteriaLookupDaoJpaImpl
 
Classes in this File Line Coverage Branch Coverage Complexity
CriteriaLookupDaoJpaImpl
0%
0/123
0%
0/78
4.312
CriteriaLookupDaoJpaImpl$1
0%
0/1
N/A
4.312
CriteriaLookupDaoJpaImpl$UnsupportedCountFlagException
0%
0/3
N/A
4.312
CriteriaLookupDaoJpaImpl$UnsupportedPredicateException
0%
0/3
N/A
4.312
 
 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.student.r2.common.criteria.impl;
 17  
 
 18  
 import org.apache.commons.lang.StringUtils;
 19  
 import org.joda.time.DateTime;
 20  
 import org.kuali.rice.core.api.criteria.AndPredicate;
 21  
 import org.kuali.rice.core.api.criteria.CompositePredicate;
 22  
 import org.kuali.rice.core.api.criteria.CountFlag;
 23  
 import org.kuali.rice.core.api.criteria.CriteriaValue;
 24  
 import org.kuali.rice.core.api.criteria.EqualIgnoreCasePredicate;
 25  
 import org.kuali.rice.core.api.criteria.EqualPredicate;
 26  
 import org.kuali.rice.core.api.criteria.GenericQueryResults;
 27  
 import org.kuali.rice.core.api.criteria.GreaterThanOrEqualPredicate;
 28  
 import org.kuali.rice.core.api.criteria.GreaterThanPredicate;
 29  
 import org.kuali.rice.core.api.criteria.InIgnoreCasePredicate;
 30  
 import org.kuali.rice.core.api.criteria.InPredicate;
 31  
 import org.kuali.rice.core.api.criteria.LessThanOrEqualPredicate;
 32  
 import org.kuali.rice.core.api.criteria.LessThanPredicate;
 33  
 import org.kuali.rice.core.api.criteria.LikePredicate;
 34  
 import org.kuali.rice.core.api.criteria.MultiValuedPredicate;
 35  
 import org.kuali.rice.core.api.criteria.NotEqualIgnoreCasePredicate;
 36  
 import org.kuali.rice.core.api.criteria.NotEqualPredicate;
 37  
 import org.kuali.rice.core.api.criteria.NotInIgnoreCasePredicate;
 38  
 import org.kuali.rice.core.api.criteria.NotInPredicate;
 39  
 import org.kuali.rice.core.api.criteria.NotLikePredicate;
 40  
 import org.kuali.rice.core.api.criteria.NotNullPredicate;
 41  
 import org.kuali.rice.core.api.criteria.NullPredicate;
 42  
 import org.kuali.rice.core.api.criteria.OrPredicate;
 43  
 import org.kuali.rice.core.api.criteria.Predicate;
 44  
 import org.kuali.rice.core.api.criteria.PropertyPathPredicate;
 45  
 import org.kuali.rice.core.api.criteria.QueryByCriteria;
 46  
 import org.kuali.rice.core.api.criteria.SingleValuedPredicate;
 47  
 import org.kuali.rice.core.framework.persistence.jpa.criteria.Criteria;
 48  
 import org.kuali.student.r2.common.criteria.LookupCustomizer;
 49  
 
 50  
 import javax.persistence.EntityManager;
 51  
 import javax.persistence.PersistenceContext;
 52  
 import javax.persistence.Query;
 53  
 import java.sql.Timestamp;
 54  
 import java.util.ArrayList;
 55  
 import java.util.HashSet;
 56  
 import java.util.List;
 57  
 import java.util.Set;
 58  
 
 59  
 /**
 60  
  * 
 61  
  * This class is a copy of the org.kuali.rice.krad.criteria.CriteriaLookupDaoJpa 
 62  
  * implementation in KRAD.
 63  
  * 
 64  
  * It should be removed once these problems are solved.
 65  
  * 
 66  
  * 1) lookup: Replace "new Criteria(queryClass.getClass().getName());" with
 67  
  *  new Criteria(queryClass.getName());
 68  
  *  
 69  
  * 2) forRowResults: jpaQuery.setFirstResult(criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() : 0);
 70  
  * instead of final int startAtIndex = criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() + 1 : 1;
 71  
  * jpaQuery.setFirstResult(startAtIndex);
 72  
  * and
 73  
  * jpaQuery.setMaxResults(criteria.getMaxResults() + 1);
 74  
  * and
 75  
  * rows.remove(criteria.getMaxResults().intValue() + 1);
 76  
  * 
 77  
  * @author Kuali Rice Team (kuali-rice@googlegroups.com)
 78  
  *
 79  
  */
 80  0
 public class CriteriaLookupDaoJpaImpl {
 81  
     @PersistenceContext
 82  
     private EntityManager entityManager;
 83  
 
 84  
     public <T> GenericQueryResults<T> lookup(final Class<T> queryClass, final QueryByCriteria criteria, LookupCustomizer<T> customizer) {
 85  0
         if (queryClass == null) {
 86  0
             throw new IllegalArgumentException("queryClass is null");
 87  
         }
 88  
 
 89  0
         if (criteria == null) {
 90  0
             throw new IllegalArgumentException("criteria is null");
 91  
         }
 92  
 
 93  0
         if (customizer == null) {
 94  0
             throw new IllegalArgumentException("customizer is null");
 95  
         }
 96  
 
 97  0
         final Criteria parent = new Criteria(queryClass.getName());
 98  
 
 99  0
         if (criteria.getPredicate() != null) {
 100  0
             Predicate predicate = customizer.applyAdditionalTransforms(criteria.getPredicate(), parent);
 101  0
             addPredicate(predicate, parent, parent, customizer);
 102  
         }
 103  
 
 104  0
         switch (criteria.getCountFlag()) {
 105  
             case ONLY:
 106  0
                 return forCountOnly(queryClass, criteria, parent);
 107  
             case NONE:
 108  0
                 return forRowResults(queryClass, criteria, parent, criteria.getCountFlag(), customizer.getResultTransform());
 109  
             case INCLUDE:
 110  0
                 return forRowResults(queryClass, criteria, parent, criteria.getCountFlag(), customizer.getResultTransform());
 111  0
             default: throw new UnsupportedCountFlagException(criteria.getCountFlag());
 112  
         }
 113  
     }
 114  
 
 115  
     /** gets results where the actual rows are requested. */
 116  
     private <T> GenericQueryResults<T> forRowResults(final Class<T> queryClass, final QueryByCriteria criteria, final Criteria jpaCriteria, CountFlag flag, LookupCustomizer.Transform<T, T> transform) {
 117  0
         final Query jpaQuery = new org.kuali.rice.core.framework.persistence.jpa.criteria.QueryByCriteria(entityManager, jpaCriteria).toQuery();
 118  0
         final GenericQueryResults.Builder<T> results = GenericQueryResults.Builder.<T>create();
 119  
 
 120  
         //ojb's is 1 based, our query api is zero based
 121  0
         jpaQuery.setFirstResult(criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() : 0);
 122  
 
 123  0
         if (criteria.getMaxResults() != null) {
 124  
             //adding one to MaxResults in order to retrieve
 125  
             //one extra row so that the MoreResultsAvailable field can be set
 126  0
             jpaQuery.setMaxResults(criteria.getMaxResults() + 1);
 127  
         }
 128  
 
 129  
         @SuppressWarnings("unchecked")
 130  0
         final List<T> rows = new ArrayList<T>(jpaQuery.getResultList());
 131  0
         if (flag == CountFlag.INCLUDE) {
 132  0
             results.setTotalRowCount(rows.size());
 133  
         }
 134  
 
 135  0
         if (criteria.getMaxResults() != null && rows.size() > criteria.getMaxResults()) {
 136  0
             results.setMoreResultsAvailable(true);
 137  
             //remove the extra row that was returned
 138  0
             rows.remove(criteria.getMaxResults().intValue() + 1);
 139  
         }
 140  
 
 141  0
         results.setResults(transformResults(rows, transform));
 142  0
         return results.build();
 143  
     }
 144  
 
 145  
     private static <T> List<T> transformResults(List<T> results, LookupCustomizer.Transform<T, T> transform) {
 146  0
         final List<T> list = new ArrayList<T>();
 147  0
         for (T r : results) {
 148  0
             list.add(transform.apply(r));
 149  
         }
 150  0
         return list;
 151  
     }
 152  
 
 153  
     /** gets results where only the count is requested. */
 154  
     private <T> GenericQueryResults<T> forCountOnly(final Class<T> queryClass, final QueryByCriteria criteria, final Criteria jpaCriteria) {
 155  0
         final Query jpaQuery = new org.kuali.rice.core.framework.persistence.jpa.criteria.QueryByCriteria(entityManager, jpaCriteria).toQuery();
 156  0
         final GenericQueryResults.Builder<T> results = GenericQueryResults.Builder.<T>create();
 157  
         // TODO : There has to be a better way to do this.
 158  0
         results.setTotalRowCount(jpaQuery.getResultList().size());
 159  
 
 160  0
         return results.build();
 161  
     }
 162  
 
 163  
     /** adds a predicate to a Criteria.*/
 164  
     private void addPredicate(Predicate p, Criteria parent, Criteria root, LookupCustomizer<?> customizer) {
 165  0
         p = customizer.applyPredicateTransforms(p, root);
 166  
 
 167  0
         if (p instanceof PropertyPathPredicate) {
 168  0
             final String pp = ((PropertyPathPredicate) p).getPropertyPath();
 169  0
             if (p instanceof NotNullPredicate) {
 170  0
                 parent.notNull(pp);
 171  0
             } else if (p instanceof NullPredicate) {
 172  0
                 parent.isNull(pp);
 173  0
             } else if (p instanceof SingleValuedPredicate) {
 174  0
                 addSingleValuePredicate((SingleValuedPredicate) p, parent);
 175  0
             } else if (p instanceof MultiValuedPredicate) {
 176  0
                 addMultiValuePredicate((MultiValuedPredicate) p, parent);
 177  
             } else {
 178  0
                 throw new UnsupportedPredicateException(p);
 179  
             }
 180  0
         } else if (p instanceof CompositePredicate) {
 181  0
             addCompositePredicate((CompositePredicate) p, parent, root, customizer);
 182  
         } else {
 183  0
             throw new UnsupportedPredicateException(p);
 184  
         }
 185  0
     }
 186  
 
 187  
     /** adds a single valued predicate to a Criteria. */
 188  
     private void addSingleValuePredicate(SingleValuedPredicate p, Criteria parent) {
 189  0
         final Object value = getVal(p.getValue());
 190  0
         final String pp = p.getPropertyPath();
 191  0
         if (p instanceof EqualPredicate) {
 192  0
             parent.eq(pp, value);
 193  0
         } else if (p instanceof EqualIgnoreCasePredicate) {
 194  0
             parent.eq(genUpperFunc(pp), ((String) value).toUpperCase());
 195  0
         } else if (p instanceof GreaterThanOrEqualPredicate) {
 196  0
             parent.gte(pp, value);
 197  0
         } else if (p instanceof GreaterThanPredicate) {
 198  0
             parent.gt(pp, value);
 199  0
         } else if (p instanceof LessThanOrEqualPredicate) {
 200  0
             parent.lte(pp, value);
 201  0
         } else if (p instanceof LessThanPredicate) {
 202  0
             parent.lt(pp, value);
 203  0
         } else if (p instanceof LikePredicate) {
 204  
             //no need to convert * or ? since ojb handles the conversion/escaping
 205  0
             parent.like(genUpperFunc(pp), ((String) value).toUpperCase());
 206  0
         } else if (p instanceof NotEqualPredicate) {
 207  0
             parent.ne(pp, value);
 208  0
         } else if (p instanceof NotEqualIgnoreCasePredicate) {
 209  0
             parent.ne(genUpperFunc(pp), ((String) value).toUpperCase());
 210  0
         } else if (p instanceof NotLikePredicate) {
 211  0
             parent.notLike(pp, value);
 212  
         } else {
 213  0
             throw new UnsupportedPredicateException(p);
 214  
         }
 215  0
     }
 216  
 
 217  
     /** adds a multi valued predicate to a Criteria. */
 218  
     private void addMultiValuePredicate(MultiValuedPredicate p, Criteria parent) {
 219  0
         final String pp = p.getPropertyPath();
 220  0
         if (p instanceof InPredicate) {
 221  0
             final Set<?> values = getVals(p.getValues());
 222  0
             parent.in(pp, values);
 223  0
         } else if (p instanceof InIgnoreCasePredicate) {
 224  0
             final Set<String> values = toUpper(getValsUnsafe(((InIgnoreCasePredicate) p).getValues()));
 225  0
             parent.in(genUpperFunc(pp), values);
 226  0
         } else if (p instanceof NotInPredicate) {
 227  0
             final Set<?> values = getVals(p.getValues());
 228  0
             parent.notIn(pp, values);
 229  0
         } else if (p instanceof NotInIgnoreCasePredicate) {
 230  0
             final Set<String> values = toUpper(getValsUnsafe(((NotInIgnoreCasePredicate) p).getValues()));
 231  0
             parent.notIn(genUpperFunc(pp), values);
 232  0
         } else {
 233  0
             throw new UnsupportedPredicateException(p);
 234  
         }
 235  0
     }
 236  
 
 237  
     /** adds a composite predicate to a Criteria. */
 238  
     private void addCompositePredicate(final CompositePredicate p, final Criteria parent, Criteria root,  LookupCustomizer<?> customizer) {
 239  0
         for (Predicate ip : p.getPredicates()) {
 240  0
             final Criteria inner = new Criteria(parent.getEntityName());
 241  0
             addPredicate(ip, inner, root, customizer);
 242  0
             if (p instanceof AndPredicate) {
 243  0
                 parent.and(inner);
 244  0
             } else if (p instanceof OrPredicate) {
 245  0
                 parent.or(inner);
 246  
             } else {
 247  0
                 throw new UnsupportedPredicateException(p);
 248  
             }
 249  0
         }
 250  0
     }
 251  
 
 252  
     private static <U extends CriteriaValue<?>> Object getVal(U toConv) {
 253  0
         Object o = toConv.getValue();
 254  0
         if (o instanceof DateTime) {
 255  0
             return new Timestamp(((DateTime) o).getMillis());
 256  
         }
 257  0
         return o;
 258  
     }
 259  
 
 260  
     //this is unsafe b/c values could be converted resulting in a classcast exception
 261  
     @SuppressWarnings("unchecked")
 262  
     private static <T, U extends CriteriaValue<T>> Set<T> getValsUnsafe(Set<? extends U> toConv) {
 263  0
         return (Set<T>) getVals(toConv);
 264  
     }
 265  
 
 266  
     private static Set<?> getVals(Set<? extends CriteriaValue<?>> toConv) {
 267  0
         final Set<Object> values = new HashSet<Object>();
 268  0
         for (CriteriaValue<?> value : toConv) {
 269  0
             values.add(getVal(value));
 270  
         }
 271  0
         return values;
 272  
     }
 273  
 
 274  
     //eliding performance for function composition....
 275  
     private static Set<String> toUpper(Set<String> strs) {
 276  0
         final Set<String> values = new HashSet<String>();
 277  0
         for (String value : strs) {
 278  0
             values.add(value.toUpperCase());
 279  
         }
 280  0
         return values;
 281  
     }
 282  
 
 283  
 
 284  
     private String genUpperFunc(String pp) {
 285  0
         if (StringUtils.contains(pp, "__JPA_ALIAS[[")) {
 286  0
             pp = "UPPER(" + pp + ")";
 287  
         } else {
 288  0
             pp = "UPPER(__JPA_ALIAS[[0]]__." + pp + ")";
 289  
         }
 290  0
         return pp;
 291  
     }
 292  
 
 293  
     /**
 294  
      * @param entityManager the entityManager to set
 295  
      */
 296  
     public void setEntityManager(EntityManager entityManager) {
 297  0
         this.entityManager = entityManager;
 298  0
     }
 299  
 
 300  
     /** this is a fatal error since this implementation should support all known predicates. */
 301  0
     private static class UnsupportedPredicateException extends RuntimeException {
 302  
         private UnsupportedPredicateException(Predicate predicate) {
 303  0
             super("Unsupported predicate [" + String.valueOf(predicate) + "]");
 304  0
         }
 305  
     }
 306  
 
 307  
     /** this is a fatal error since this implementation should support all known count flags. */
 308  0
     private static class UnsupportedCountFlagException extends RuntimeException {
 309  
         private UnsupportedCountFlagException(CountFlag flag) {
 310  0
             super("Unsupported predicate [" + String.valueOf(flag) + "]");
 311  0
         }
 312  
     }
 313  
 }