Example usage for javax.persistence.criteria CriteriaBuilder greaterThanOrEqualTo

List of usage examples for javax.persistence.criteria CriteriaBuilder greaterThanOrEqualTo

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder greaterThanOrEqualTo.

Prototype

<Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(Expression<? extends Y> x, Y y);

Source Link

Document

Create a predicate for testing whether the first argument is greater than or equal to the second.

Usage

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status,
        DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset,
        Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot
            .fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
    Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
            .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
            JoinType.LEFT);//ww  w . j a v a 2s .c  o m
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department,
            JoinType.LEFT);
    Predicate predicate = cb.conjunction();
    if (coordinatorUserId != null) {
        Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator;
        predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId));
    }
    if (reasonType != null) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType));
    }
    if (status != null) {
        if (status.indexOf(":") < 0) {
            predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
        } else {
            String[] statusList = status.split(":");
            predicate = cb.and(predicate,
                    applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList)));
        }
    }

    if (startBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore));
    }

    if (startAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter));
    }

    if (endBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore));
    }

    if (endAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter));
    }

    cq.where(predicate);

    List<Order> orders = new ArrayList<>();
    if (orderByParam != null) {
        for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) {
            Order order = null;
            if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) {
                order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime));
            }
            if (order != null && !orderBy.isAsc()) {
                order = order.reverse();
            }
            if (order != null) {
                orders.add(order);
            }
        }

    }
    if (orders.size() == 0) {
        cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)));
    } else {
        cq.orderBy(orders);
    }

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

    if (offset != null) {
        query.setFirstResult(offset);
    }
    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("applications", principalExt);

    return query.getResultList();
}

From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java

/**
 * @see ??JPA/*from   w  w w . j  a v  a  2  s.  c o  m*/
 * @param filters
 * @param entityClazz
 * @param isDistinct  trueSQLdistinctfalse?
 * @return
 */
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) {
    return new Specification<T>() {
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (orderParams != null && orderParams.size() > 0) {
                /*
                CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
                Root<Foo> from = criteriaQuery.from(Foo.class);
                CriteriaQuery<Foo> select = criteriaQuery.select(from);
                criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
                */
                List<Order> orders = new ArrayList<Order>(orderParams.size());
                for (OrderParam orderParam : orderParams) {
                    if (orderParam != null && orderParam.getField() != null) {
                        String fields[] = StringUtil.split(orderParam.getField(), '.');
                        Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]);
                        for (int i = 1, len = fields.length; i < len; ++i) {
                            expression = expression.get(fields[i]);
                        }
                        if (expression != null) {
                            Order order = (orderParam.getType() == null
                                    || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression)
                                            : builder.desc(expression);
                            orders.add(order);
                            //                        query.orderBy(order);
                        }
                    }
                }
                query.orderBy(orders);
            }
            query.distinct(isDistinct);
            if (Collections3.isNotEmpty(filters)) {
                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, '.');
                    Path expression = null;

                    //////  ?
                    boolean hasJoin = names[0].startsWith("[join]");
                    String fn = hasJoin ? names[0].substring(6) : names[0];
                    boolean isNotDateType = !(filter.value instanceof Date);
                    try {
                        expression = hasJoin ? root.join(fn) : root.get(fn);
                        if (isNotDateType && isDateType(expression.getJavaType())) {
                            // filter.value??
                            filter.value = parseDate(filter.value.toString(), filter.operator);
                        }
                    } catch (Exception e) {
                        //                     logger.error(e.getMessage(), e);
                        continue; // ??
                    }
                    boolean isPropertyNotValid = false;
                    for (int i = 1; i < names.length; i++) {
                        try {
                            expression = expression.get(names[i]);
                            if (isNotDateType && isDateType(expression.getJavaType())) {
                                filter.value = parseDate(filter.value.toString(), filter.operator);
                            }
                        } catch (Exception e) {
                            //                        logger.error(e.getMessage(), e);
                            isPropertyNotValid = true; // 
                            break; // ??
                        }
                    }
                    if (expression == null || isPropertyNotValid) {
                        continue;
                    }
                    ///////

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case ORLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.or(like));
                        }

                        break;
                    case ANDLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case ANDNOTLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notLike(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case OREQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.equal(expression, values[i]);
                            }
                            predicates.add(builder.or(like));
                        }
                        break;

                    case ANDNOTEQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notEqual(expression, values[i]);
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case NOTEQ:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                        break;
                    case NOTLIKE:
                        predicates.add(builder.notLike(expression, "%" + filter.value + "%"));
                        break;
                    case NULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NOTNULL:
                        predicates.add(builder.isNotNull(expression));
                        break;
                    //                  case IN:
                    //                     predicates.add(builder.in(expression).in(values));
                    //                     break;
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}

From source file:org.apache.ranger.service.XTrxLogService.java

private Predicate generatePredicate(SearchCriteria searchCriteria, EntityManager em,
        CriteriaBuilder criteriaBuilder, Root<VXXTrxLog> rootEntityType) {
    Predicate predicate = criteriaBuilder.conjunction();
    Map<String, Object> paramList = searchCriteria.getParamList();
    if (CollectionUtils.isEmpty(paramList)) {
        return predicate;
    }// w  ww . j  a va 2  s  .c  om

    Metamodel entityMetaModel = em.getMetamodel();
    EntityType<VXXTrxLog> entityType = entityMetaModel.entity(VXXTrxLog.class);

    for (Map.Entry<String, Object> entry : paramList.entrySet()) {
        String key = entry.getKey();
        for (SearchField searchField : searchFields) {
            if (!key.equalsIgnoreCase(searchField.getClientFieldName())) {
                continue;
            }

            String fieldName = searchField.getFieldName();
            if (!StringUtils.isEmpty(fieldName)) {
                fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1)
                        : fieldName;
            }

            Object paramValue = entry.getValue();
            boolean isListValue = false;
            if (paramValue != null && paramValue instanceof Collection) {
                isListValue = true;
            }

            // build where clause depending upon given parameters
            if (SearchField.DATA_TYPE.STRING.equals(searchField.getDataType())) {
                // build where clause for String datatypes
                SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                if (attr != null) {
                    Predicate stringPredicate = null;
                    if (SearchField.SEARCH_TYPE.PARTIAL.equals(searchField.getSearchType())) {
                        String val = "%" + paramValue + "%";
                        stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val);
                    } else {
                        stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue);
                    }
                    predicate = criteriaBuilder.and(predicate, stringPredicate);
                }

            } else if (SearchField.DATA_TYPE.INT_LIST.equals(searchField.getDataType())
                    || isListValue && SearchField.DATA_TYPE.INTEGER.equals(searchField.getDataType())) {
                // build where clause for integer lists or integers datatypes
                Collection<Number> intValueList = null;
                if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) {
                    intValueList = new ArrayList<Number>();
                    intValueList.add((Number) paramValue);
                } else {
                    intValueList = (Collection<Number>) paramValue;
                }
                for (Number value : intValueList) {
                    SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                    if (attr != null) {
                        Predicate intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value);
                        predicate = criteriaBuilder.and(predicate, intPredicate);
                    }
                }

            } else if (SearchField.DATA_TYPE.DATE.equals(searchField.getDataType())) {
                // build where clause for date datatypes
                Date fieldValue = (Date) paramList.get(searchField.getClientFieldName());
                if (fieldValue != null && searchField.getCustomCondition() == null) {
                    SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                    Predicate datePredicate = null;
                    if (SearchField.SEARCH_TYPE.LESS_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.LESS_EQUAL_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.GREATER_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr),
                                fieldValue);
                    } else {
                        datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
                    }
                    predicate = criteriaBuilder.and(predicate, datePredicate);
                }
            }
        }
    }
    return predicate;
}

From source file:org.broadleafcommerce.admin.server.service.handler.SkuRestrictionFactoryImpl.java

@Override
public Restriction getRestriction(final String type, String propertyId) {
    final Restriction delegateRestriction = delegate.getRestriction(type, propertyId);
    return new Restriction().withFilterValueConverter(delegateRestriction.getFilterValueConverter())
            .withPredicateProvider(new PredicateProvider() {
                @Override/*ww w .j a v a 2s .  com*/
                public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
                        From root, String ceilingEntity, String fullPropertyName, Path explicitPath,
                        List directValues) {
                    FieldPath fieldPath = fieldPathBuilder.getFieldPath(root, fullPropertyName);
                    if ((StringUtils.isNotEmpty(skuPropertyPrefix)
                            && fullPropertyName.startsWith(skuPropertyPrefix))
                            || CollectionUtils.isEmpty(fieldPath.getAssociationPath())) {
                        Path targetPropertyPath = fieldPathBuilder.getPath(root, fieldPath, builder);
                        Path defaultSkuPropertyPath = fieldPathBuilder.getPath(root,
                                DEFAULT_SKU_PATH_PREFIX + fullPropertyName, builder);
                        Path productPath = fieldPathBuilder.getPath(root, "product", builder);
                        Predicate propertyExpression;
                        Predicate defaultSkuExpression;
                        if (delegateRestriction.getPredicateProvider() instanceof LikePredicateProvider) {
                            propertyExpression = builder.like(builder.lower(targetPropertyPath),
                                    ((String) directValues.get(0)).toLowerCase());
                            defaultSkuExpression = builder.like(builder.lower(defaultSkuPropertyPath),
                                    ((String) directValues.get(0)).toLowerCase());
                        } else if (delegateRestriction
                                .getPredicateProvider() instanceof IsNullPredicateProvider) {
                            propertyExpression = builder.isNull(targetPropertyPath);
                            defaultSkuExpression = builder.isNull(defaultSkuPropertyPath);
                        } else if (delegateRestriction
                                .getPredicateProvider() instanceof BetweenDatePredicateProvider) {
                            if (directValues.size() == 2) {
                                if (directValues.get(0) == null) {
                                    propertyExpression = builder.lessThan(targetPropertyPath,
                                            (Comparable) directValues.get(1));
                                    defaultSkuExpression = builder.lessThan(defaultSkuPropertyPath,
                                            (Comparable) directValues.get(1));
                                } else if (directValues.get(1) == null) {
                                    propertyExpression = builder.greaterThanOrEqualTo(targetPropertyPath,
                                            (Comparable) directValues.get(0));
                                    defaultSkuExpression = builder.greaterThanOrEqualTo(defaultSkuPropertyPath,
                                            (Comparable) directValues.get(0));
                                } else {
                                    propertyExpression = builder.between(targetPropertyPath,
                                            (Comparable) directValues.get(0), (Comparable) directValues.get(1));
                                    defaultSkuExpression = builder.between(defaultSkuPropertyPath,
                                            (Comparable) directValues.get(0), (Comparable) directValues.get(1));
                                }
                            } else {
                                propertyExpression = builder.equal(targetPropertyPath, directValues.get(0));
                                defaultSkuExpression = builder.equal(defaultSkuPropertyPath,
                                        directValues.get(0));
                            }
                        } else if (delegateRestriction
                                .getPredicateProvider() instanceof BetweenPredicateProvider) {
                            if (directValues.size() > 1) {
                                propertyExpression = builder.between(targetPropertyPath,
                                        (Comparable) directValues.get(0), (Comparable) directValues.get(1));
                                defaultSkuExpression = builder.between(defaultSkuPropertyPath,
                                        (Comparable) directValues.get(0), (Comparable) directValues.get(1));
                            } else {
                                propertyExpression = builder.equal(targetPropertyPath, directValues.get(0));
                                defaultSkuExpression = builder.equal(defaultSkuPropertyPath,
                                        directValues.get(0));
                            }
                        } else if (delegateRestriction
                                .getPredicateProvider() instanceof CollectionSizeEqualPredicateProvider) {
                            propertyExpression = builder.equal(builder.size(targetPropertyPath),
                                    directValues.get(0));
                            defaultSkuExpression = builder.equal(builder.size(defaultSkuPropertyPath),
                                    directValues.get(0));
                        } else if (delegateRestriction.getPredicateProvider() instanceof EqPredicateProvider) {
                            propertyExpression = builder.equal(targetPropertyPath, directValues.get(0));
                            defaultSkuExpression = builder.equal(defaultSkuPropertyPath, directValues.get(0));
                        } else {
                            throw new IllegalArgumentException("Unknown PredicateProvider instance: "
                                    + delegateRestriction.getPredicateProvider().getClass().getName());
                        }

                        return buildCompositePredicate(builder, targetPropertyPath, productPath,
                                propertyExpression, defaultSkuExpression);
                    }
                    return delegateRestriction.getPredicateProvider().buildPredicate(builder, fieldPathBuilder,
                            root, ceilingEntity, fullPropertyName, explicitPath, directValues);
                }
            });
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}/*from   w w w  . j  a  v a 2 s . co m*/
 */
@Override
public ExpectedPartitionValueEntity getExpectedPartitionValue(
        ExpectedPartitionValueKey expectedPartitionValueKey, int offset) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ExpectedPartitionValueEntity> criteria = builder
            .createQuery(ExpectedPartitionValueEntity.class);

    // The criteria root is the expected partition value.
    Root<ExpectedPartitionValueEntity> expectedPartitionValueEntity = criteria
            .from(ExpectedPartitionValueEntity.class);

    // Join to the other tables we can filter on.
    Join<ExpectedPartitionValueEntity, PartitionKeyGroupEntity> partitionKeyGroupEntity = expectedPartitionValueEntity
            .join(ExpectedPartitionValueEntity_.partitionKeyGroup);

    // Add a restriction to filter case insensitive groups that match the user specified group.
    Predicate whereRestriction = builder.equal(
            builder.upper(partitionKeyGroupEntity.get(PartitionKeyGroupEntity_.partitionKeyGroupName)),
            expectedPartitionValueKey.getPartitionKeyGroupName().toUpperCase());

    // Depending on the offset, we might need to order the records in the query.
    Order orderByExpectedPartitionValue = null;

    // Add additional restrictions to handle expected partition value and an optional offset.
    if (offset == 0) {
        // Since there is no offset, we need to match the expected partition value exactly.
        whereRestriction = builder.and(whereRestriction,
                builder.equal(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                        expectedPartitionValueKey.getExpectedPartitionValue()));
    } else if (offset > 0) {
        // For a positive offset value, add a restriction to filter expected partition values that are >= the user specified expected partition value.
        whereRestriction = builder.and(whereRestriction,
                builder.greaterThanOrEqualTo(
                        expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                        expectedPartitionValueKey.getExpectedPartitionValue()));

        // Order by expected partition value in ascending order.
        orderByExpectedPartitionValue = builder
                .asc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));
    } else {
        // For a negative offset value, add a restriction to filter expected partition values that are <= the user specified expected partition value.
        whereRestriction = builder.and(whereRestriction,
                builder.lessThanOrEqualTo(
                        expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                        expectedPartitionValueKey.getExpectedPartitionValue()));

        // Order by expected partition value in descending order.
        orderByExpectedPartitionValue = builder
                .desc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));
    }

    // Add the clauses for the query and execute the query.
    if (offset == 0) {
        criteria.select(expectedPartitionValueEntity).where(whereRestriction);

        return executeSingleResultQuery(criteria, String.format(
                "Found more than one expected partition value with parameters {partitionKeyGroupName=\"%s\", expectedPartitionValue=\"%s\"}.",
                expectedPartitionValueKey.getPartitionKeyGroupName(),
                expectedPartitionValueKey.getExpectedPartitionValue()));
    } else {
        criteria.select(expectedPartitionValueEntity).where(whereRestriction)
                .orderBy(orderByExpectedPartitionValue);

        List<ExpectedPartitionValueEntity> resultList = entityManager.createQuery(criteria)
                .setFirstResult(Math.abs(offset)).setMaxResults(1).getResultList();

        return resultList.size() > 0 ? resultList.get(0) : null;
    }
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}//from   w  w w .j  a va2 s.co  m
 */
@Override
public List<ExpectedPartitionValueEntity> getExpectedPartitionValuesByGroupAndRange(
        String partitionKeyGroupName, PartitionValueRange partitionValueRange) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ExpectedPartitionValueEntity> criteria = builder
            .createQuery(ExpectedPartitionValueEntity.class);

    // The criteria root is the expected partition value.
    Root<ExpectedPartitionValueEntity> expectedPartitionValueEntity = criteria
            .from(ExpectedPartitionValueEntity.class);

    // Join to the other tables we can filter on.
    Join<ExpectedPartitionValueEntity, PartitionKeyGroupEntity> partitionKeyGroupEntity = expectedPartitionValueEntity
            .join(ExpectedPartitionValueEntity_.partitionKeyGroup);

    // Add a restriction to filter case insensitive groups that match the user specified group.
    Predicate whereRestriction = builder.equal(
            builder.upper(partitionKeyGroupEntity.get(PartitionKeyGroupEntity_.partitionKeyGroupName)),
            partitionKeyGroupName.toUpperCase());

    // If we have a possible partition value range, we need to add additional restrictions.
    if (partitionValueRange != null) {
        // Add a restriction to filter values that are >= the user specified range start value.
        if (StringUtils.isNotBlank(partitionValueRange.getStartPartitionValue())) {
            whereRestriction = builder.and(whereRestriction,
                    builder.greaterThanOrEqualTo(
                            expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                            partitionValueRange.getStartPartitionValue()));
        }

        // Add a restriction to filter values that are <= the user specified range end value.
        if (StringUtils.isNotBlank(partitionValueRange.getEndPartitionValue())) {
            whereRestriction = builder.and(whereRestriction,
                    builder.lessThanOrEqualTo(
                            expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                            partitionValueRange.getEndPartitionValue()));
        }
    }

    // Order the results by partition value.
    Order orderByValue = builder
            .asc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));

    // Add the clauses for the query.
    criteria.select(expectedPartitionValueEntity).where(whereRestriction).orderBy(orderByValue);

    // Execute the query and return the results.
    return entityManager.createQuery(criteria).getResultList();
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Retrieves partition value per specified parameters that includes the aggregate function.
 *
 * @param partitionColumnPosition the partition column position (1-based numbering)
 * @param businessObjectFormatKey the business object format key (case-insensitive). If a business object format version isn't specified, the latest
 * available format version for each partition value will be used.
 * @param businessObjectDataVersion the business object data version. If a business object data version isn't specified, the latest data version for each
 * partition value will be used./*from   w w w .jav  a 2s.  c om*/
 * @param storageName the name of the storage where the business object data storage unit is located (case-insensitive)
 * @param aggregateFunction the aggregate function to use against partition values
 * @param upperBoundPartitionValue the optional inclusive upper bound for the maximum available partition value
 * @param lowerBoundPartitionValue the optional inclusive lower bound for the maximum available partition value
 *
 * @return the partition value
 */
private String getBusinessObjectDataPartitionValue(int partitionColumnPosition,
        BusinessObjectFormatKey businessObjectFormatKey, Integer businessObjectDataVersion, String storageName,
        AggregateFunction aggregateFunction, String upperBoundPartitionValue, String lowerBoundPartitionValue) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

    // The criteria root is the business object data.
    Root<BusinessObjectDataEntity> businessObjectDataEntity = criteria.from(BusinessObjectDataEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);

    // Create the path.
    Expression<String> partitionValue;
    SingularAttribute<BusinessObjectDataEntity, String> singleValuedAttribute = BUSINESS_OBJECT_DATA_PARTITIONS
            .get(partitionColumnPosition - 1);
    switch (aggregateFunction) {
    case GREATEST:
        partitionValue = builder.greatest(businessObjectDataEntity.get(singleValuedAttribute));
        break;
    case LEAST:
        partitionValue = builder.least(businessObjectDataEntity.get(singleValuedAttribute));
        break;
    default:
        throw new IllegalArgumentException("Invalid aggregate function found: \"" + aggregateFunction + "\".");
    }

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate mainQueryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectFormatKey.getNamespace().toUpperCase());
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectFormatKey.getBusinessObjectDefinitionName().toUpperCase()));
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
                    businessObjectFormatKey.getBusinessObjectFormatUsage().toUpperCase()));
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)),
                    businessObjectFormatKey.getBusinessObjectFormatFileType().toUpperCase()));

    // If a business object format version was specified, use it.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.equal(
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion),
                        businessObjectFormatKey.getBusinessObjectFormatVersion()));
    }

    // If a data version was specified, use it. Otherwise, use the latest one.
    if (businessObjectDataVersion != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.equal(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.version), businessObjectDataVersion));
    } else {
        // Business object data version is not specified, so get the latest one regardless of the business object data status in the specified storage.
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntity, businessObjectFormatEntity, null, storageEntity);

        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.in(businessObjectDataEntity.get(BusinessObjectDataEntity_.version)).value(subQuery));
    }

    // Add an inclusive upper bound partition value restriction if specified.
    if (upperBoundPartitionValue != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.lessThanOrEqualTo(
                businessObjectDataEntity.get(singleValuedAttribute), upperBoundPartitionValue));
    }

    // Add an inclusive lower bound partition value restriction if specified.
    if (lowerBoundPartitionValue != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.greaterThanOrEqualTo(
                businessObjectDataEntity.get(singleValuedAttribute), lowerBoundPartitionValue));
    }

    // Add a storage name restriction to the query where clause.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase()));

    criteria.select(partitionValue).where(mainQueryRestriction);

    return entityManager.createQuery(criteria).getSingleResult();
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * TODO: Make this method the main body of getStorageUploadStats once we migrate away from Oracle getStorageUploadStats TODO:    that leverages the storage
 * file view to query. This method is meant to be database agnostic.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range//  ww w. j a va  2  s.c  o  m
 *
 * @return the upload statistics
 */
private StorageDailyUploadStats getStorageUploadStatsDatabaseAgnostic(
        StorageAlternateKeyDto storageAlternateKey, DateRangeDto dateRange) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    Root<StorageFileViewEntity> storageFileViewEntity = criteria.from(StorageFileViewEntity.class);

    Path<Date> createdDate = storageFileViewEntity.get(StorageFileViewEntity_.createdDate);

    Expression<Long> totalFilesExpression = builder
            .count(storageFileViewEntity.get(StorageFileViewEntity_.storageFileId));
    Expression<Long> totalBytesExpression = builder
            .sum(storageFileViewEntity.get(StorageFileViewEntity_.fileSizeInBytes));

    Predicate storageNameRestriction = builder.equal(
            builder.upper(storageFileViewEntity.get(StorageFileViewEntity_.storageCode)),
            storageAlternateKey.getStorageName().toUpperCase());
    Predicate createDateRestriction = builder.and(
            builder.greaterThanOrEqualTo(createdDate, dateRange.getLowerDate()),
            builder.lessThanOrEqualTo(createdDate, dateRange.getUpperDate()));

    criteria.multiselect(createdDate, totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

    List<Expression<?>> grouping = new ArrayList<>();
    grouping.add(createdDate);

    criteria.groupBy(grouping);

    criteria.orderBy(builder.asc(createdDate));

    // Retrieve and return the storage upload statistics.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();
    StorageDailyUploadStats uploadStats = new StorageDailyUploadStats();

    for (Tuple tuple : tuples) {
        StorageDailyUploadStat uploadStat = new StorageDailyUploadStat();
        uploadStats.getStorageDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(DmDateUtils.getXMLGregorianCalendarValue(tuple.get(createdDate)));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * TODO: Remove this method once we migrate away from Oracle getStorageUploadStats that uses Oracle specific 'trunc' function.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range//from  w  w  w.j  a va  2 s. c o  m
 *
 * @return the upload statistics
 */
private StorageDailyUploadStats getStorageUploadStatsOracle(StorageAlternateKeyDto storageAlternateKey,
        DateRangeDto dateRange) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the storage file.
    Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity
            .join(StorageFileEntity_.storageUnit);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);

    // Create paths.
    Expression<Date> truncCreatedOnDateExpression = builder.function("trunc", Date.class,
            storageFileEntity.get(StorageFileEntity_.createdOn));
    Expression<Long> totalFilesExpression = builder.count(storageFileEntity.get(StorageFileEntity_.id));
    Expression<Long> totalBytesExpression = builder
            .sum(storageFileEntity.get(StorageFileEntity_.fileSizeBytes));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageAlternateKey.getStorageName().toUpperCase());
    Predicate createDateRestriction = builder.and(
            builder.greaterThanOrEqualTo(truncCreatedOnDateExpression, dateRange.getLowerDate()),
            builder.lessThanOrEqualTo(truncCreatedOnDateExpression, dateRange.getUpperDate()));

    criteria.multiselect(truncCreatedOnDateExpression, totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

    // Create the group by clause.
    List<Expression<?>> grouping = new ArrayList<>();

    grouping.add(truncCreatedOnDateExpression);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(truncCreatedOnDateExpression));

    // Retrieve and return the storage upload statistics.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();
    StorageDailyUploadStats uploadStats = new StorageDailyUploadStats();

    for (Tuple tuple : tuples) {
        StorageDailyUploadStat uploadStat = new StorageDailyUploadStat();
        uploadStats.getStorageDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(
                DmDateUtils.getXMLGregorianCalendarValue(tuple.get(truncCreatedOnDateExpression)));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * TODO: Make this method the main body of getStorageUploadStatsByBusinessObjectDefinition once we migrate away from Oracle TODO:
 * getStorageUploadStatsByBusinessObjectDefinition that uses storage file view. This method is meant to be database agnostic.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range/*w  w  w  .j  a v  a  2 s.  co m*/
 *
 * @return the upload statistics
 */
private StorageBusinessObjectDefinitionDailyUploadStats getStorageUploadStatsByBusinessObjectDefinitionDatabaseAgnostic(
        StorageAlternateKeyDto storageAlternateKey, DateRangeDto dateRange) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    Root<StorageFileViewEntity> storageFileViewEntity = criteria.from(StorageFileViewEntity.class);

    Path<String> namespaceCode = storageFileViewEntity.get(StorageFileViewEntity_.namespaceCode);
    Path<String> dataProviderCode = storageFileViewEntity.get(StorageFileViewEntity_.dataProviderCode);
    Path<String> businessObjectDefinitionName = storageFileViewEntity
            .get(StorageFileViewEntity_.businessObjectDefinitionName);
    Path<Date> createdDate = storageFileViewEntity.get(StorageFileViewEntity_.createdDate);
    Expression<Long> totalFilesExpression = builder
            .count(storageFileViewEntity.get(StorageFileViewEntity_.storageFileId));
    Expression<Long> totalBytesExpression = builder
            .sum(storageFileViewEntity.get(StorageFileViewEntity_.fileSizeInBytes));

    Predicate storageNameRestriction = builder.equal(
            builder.upper(storageFileViewEntity.get(StorageFileViewEntity_.storageCode)),
            storageAlternateKey.getStorageName().toUpperCase());
    Predicate createDateRestriction = builder.and(
            builder.greaterThanOrEqualTo(createdDate, dateRange.getLowerDate()),
            builder.lessThanOrEqualTo(createdDate, dateRange.getUpperDate()));

    criteria.multiselect(createdDate, namespaceCode, dataProviderCode, businessObjectDefinitionName,
            totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

    // Create the group by clause.
    List<Expression<?>> grouping = new ArrayList<>();
    grouping.add(createdDate);
    grouping.add(namespaceCode);
    grouping.add(dataProviderCode);
    grouping.add(businessObjectDefinitionName);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(createdDate), builder.asc(namespaceCode), builder.asc(dataProviderCode),
            builder.asc(businessObjectDefinitionName));

    // Retrieve and return the storage upload statistics.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();
    StorageBusinessObjectDefinitionDailyUploadStats uploadStats = new StorageBusinessObjectDefinitionDailyUploadStats();

    for (Tuple tuple : tuples) {
        StorageBusinessObjectDefinitionDailyUploadStat uploadStat = new StorageBusinessObjectDefinitionDailyUploadStat();
        uploadStats.getStorageBusinessObjectDefinitionDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(DmDateUtils.getXMLGregorianCalendarValue(tuple.get(createdDate)));
        uploadStat.setNamespace(tuple.get(namespaceCode));
        uploadStat.setDataProviderName(tuple.get(dataProviderCode));
        uploadStat.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionName));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}