Example usage for javax.persistence.criteria CriteriaBuilder lessThan

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

Introduction

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

Prototype

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

Source Link

Document

Create a predicate for testing whether the first argument is less than the second.

Usage

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//from  w  w  w  .  java 2  s  .c o  m
                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.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachActiveRestriction(Date currentDate, Path<? extends Product> product,
        Path<? extends Sku> sku, List<Predicate> restrictions) {
    CriteriaBuilder builder = em.getCriteriaBuilder();

    // Add the product archived status flag restriction
    restrictions.add(builder.or(builder.isNull(product.get("archiveStatus").get("archived")),
            builder.equal(product.get("archiveStatus").get("archived"), 'N')));

    // Add the active start/end date restrictions
    restrictions.add(builder.lessThan(sku.get("activeStartDate").as(Date.class), currentDate));
    restrictions.add(builder.or(builder.isNull(sku.get("activeEndDate")),
            builder.greaterThan(sku.get("activeEndDate").as(Date.class), currentDate)));
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachSearchCriteria(SearchCriteria searchCriteria, From<?, ? extends Product> product,
        From<?, ? extends Sku> sku, List<Predicate> restrictions) {
    CriteriaBuilder builder = em.getCriteriaBuilder();

    // Build out the filter criteria from the users request
    for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) {
        String key = entry.getKey();
        List<String> eqValues = new ArrayList<String>();
        List<String[]> rangeValues = new ArrayList<String[]>();

        // Determine which path is the appropriate one to use
        Path<?> pathToUse;/*  w w  w. ja v a 2  s. c  o m*/
        if (key.contains("defaultSku.")) {
            pathToUse = sku;
            key = key.substring("defaultSku.".length());
        } else if (key.contains("productAttributes.")) {
            pathToUse = product.join("productAttributes");

            key = key.substring("productAttributes.".length());
            restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key));

            key = "value";
        } else if (key.contains("product.")) {
            pathToUse = product;
            key = key.substring("product.".length());
        } else {
            // We don't know which path this facet is built on - resolves previous bug that attempted
            // to attach search facet to any query parameter
            continue;
        }

        // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form
        // key=range[minRange:maxRange]. Figure out what type of check this is
        for (String value : entry.getValue()) {
            if (value.contains("range[")) {
                String[] rangeValue = new String[] {
                        value.substring(value.indexOf("[") + 1, value.indexOf(":")),
                        value.substring(value.indexOf(":") + 1, value.indexOf("]")) };
                rangeValues.add(rangeValue);
            } else {
                eqValues.add(value);
            }
        }

        // Add the equality range restriction with the "in" builder. That means that the query string
        // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob
        if (eqValues.size() > 0) {
            restrictions.add(pathToUse.get(key).in(eqValues));
        }

        // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together,
        // such that specifying range[0:5] and range[10:null] for the same field would match items
        // that were valued between 0 and 5 OR over 10 for that field
        List<Predicate> rangeRestrictions = new ArrayList<Predicate>();
        for (String[] range : rangeValues) {
            BigDecimal min = new BigDecimal(range[0]);
            BigDecimal max = null;
            if (range[1] != null && !range[1].equals("null")) {
                max = new BigDecimal(range[1]);
            }

            Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min);
            Predicate maxRange = null;
            if (max != null) {
                maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max);
                rangeRestrictions.add(builder.and(minRange, maxRange));
            } else {
                rangeRestrictions.add(minRange);
            }
        }

        if (rangeRestrictions.size() > 0) {
            restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()])));
        }
    }
}

From source file:org.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java

@Override
public Map<BusinessObjectDataEntity, StoragePolicyEntity> getBusinessObjectDataEntitiesMatchingStoragePolicies(
        StoragePolicyPriorityLevel storagePolicyPriorityLevel, List<String> supportedBusinessObjectDataStatuses,
        int storagePolicyTransitionMaxAllowedAttempts, int startPosition, int maxResult) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object data along with the storage policy.
    Root<BusinessObjectDataEntity> businessObjectDataEntityRoot = criteria.from(BusinessObjectDataEntity.class);
    Root<StoragePolicyEntity> storagePolicyEntityRoot = criteria.from(StoragePolicyEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.businessObjectFormat);

    // Create main query restrictions based on the specified parameters.
    List<Predicate> predicates = new ArrayList<>();

    // Add restriction on business object definition.
    predicates.add(storagePolicyPriorityLevel.isBusinessObjectDefinitionIsNull()
            ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.businessObjectDefinitionId))
            : builder.equal(//from  w  w  w.  ja v  a2s .  co  m
                    businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.businessObjectDefinitionId),
                    storagePolicyEntityRoot.get(StoragePolicyEntity_.businessObjectDefinitionId)));

    // Add restriction on business object format usage.
    predicates.add(storagePolicyPriorityLevel.isUsageIsNull()
            ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.usage))
            : builder.equal(
                    builder.upper(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                    builder.upper(storagePolicyEntityRoot.get(StoragePolicyEntity_.usage))));

    // Add restriction on business object format file type.
    predicates.add(storagePolicyPriorityLevel.isFileTypeIsNull()
            ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.fileType))
            : builder.equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.fileTypeCode),
                    storagePolicyEntityRoot.get(StoragePolicyEntity_.fileTypeCode)));

    // Add restriction on storage policy filter storage.
    predicates.add(builder.equal(storageUnitEntityJoin.get(StorageUnitEntity_.storageName),
            storagePolicyEntityRoot.get(StoragePolicyEntity_.storageName)));

    // Add restriction on storage policy latest version flag.
    predicates.add(builder.isTrue(storagePolicyEntityRoot.get(StoragePolicyEntity_.latestVersion)));

    // Add restriction on storage policy status.
    predicates.add(builder.equal(storagePolicyEntityRoot.get(StoragePolicyEntity_.statusCode),
            StoragePolicyStatusEntity.ENABLED));

    // Add restriction on supported business object data statuses.
    predicates.add(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.statusCode)
            .in(supportedBusinessObjectDataStatuses));

    // Add restrictions as per storage policy transition type.
    predicates.add(
            builder.equal(storagePolicyEntityRoot.get(StoragePolicyEntity_.storagePolicyTransitionTypeCode),
                    StoragePolicyTransitionTypeEntity.GLACIER));
    predicates.add(storageUnitEntityJoin.get(StorageUnitEntity_.statusCode)
            .in(Lists.newArrayList(StorageUnitStatusEntity.ENABLED, StorageUnitStatusEntity.ARCHIVING)));

    // If specified, add restriction on maximum allowed attempts for a storage policy transition.
    if (storagePolicyTransitionMaxAllowedAttempts > 0) {
        predicates.add(builder.or(
                builder.isNull(
                        storageUnitEntityJoin.get(StorageUnitEntity_.storagePolicyTransitionFailedAttempts)),
                builder.lessThan(
                        storageUnitEntityJoin.get(StorageUnitEntity_.storagePolicyTransitionFailedAttempts),
                        storagePolicyTransitionMaxAllowedAttempts)));
    }

    // Order the results by business object data "created on" value.
    Order orderByCreatedOn = builder.asc(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.createdOn));

    // Add the select clause to the main query.
    criteria.multiselect(businessObjectDataEntityRoot, storagePolicyEntityRoot);

    // Add the where clause to the main query.
    criteria.where(predicates.toArray(new Predicate[] {}));

    // Add the order by clause to the main query.
    criteria.orderBy(orderByCreatedOn);

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).setFirstResult(startPosition)
            .setMaxResults(maxResult).getResultList();

    // Populate the result map from the returned tuples (i.e. 1 tuple for each row).
    Map<BusinessObjectDataEntity, StoragePolicyEntity> result = new LinkedHashMap<>();
    for (Tuple tuple : tuples) {
        // Since multiple storage policies can contain identical filters, we add the below check to select each business object data instance only once.
        if (!result.containsKey(tuple.get(businessObjectDataEntityRoot))) {
            result.put(tuple.get(businessObjectDataEntityRoot), tuple.get(storagePolicyEntityRoot));
        }
    }

    return result;
}

From source file:org.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java

/**
 * Apply retention expiration filter to the main query predicate.
 *
 * @param businessObjectDataSearchKey the business object data search key
 * @param businessObjectDataEntityRoot the criteria root which is a business object data entity
 * @param businessObjectFormatEntityJoin the join with the business object format table
 * @param builder the criteria builder// w  ww  .j a v a2  s  .co m
 * @param mainQueryPredicate the main query predicate to be updated
 *
 * @return the updated main query predicate
 */
private Predicate applyRetentionExpirationFilter(BusinessObjectDataSearchKey businessObjectDataSearchKey,
        Root<BusinessObjectDataEntity> businessObjectDataEntityRoot,
        Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin,
        CriteriaBuilder builder, Predicate mainQueryPredicate) {
    // Create a business object definition key per specified search key.
    BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey(
            businessObjectDataSearchKey.getNamespace(),
            businessObjectDataSearchKey.getBusinessObjectDefinitionName());

    // Get latest versions of all business object formats that registered with the business object definition.
    List<BusinessObjectFormatEntity> businessObjectFormatEntities = businessObjectFormatDao
            .getLatestVersionBusinessObjectFormatsByBusinessObjectDefinition(businessObjectDefinitionKey);

    // Create a result predicate to join all retention expiration predicates created per selected business object formats.
    Predicate businessObjectDefinitionRetentionExpirationPredicate = null;

    // Get the current database timestamp to be used to select expired business object data per BDATA_RETENTION_DATE retention type.
    Timestamp currentTimestamp = getCurrentTimestamp();

    // Create a predicate for each business object format with the retention information.
    for (BusinessObjectFormatEntity businessObjectFormatEntity : businessObjectFormatEntities) {
        if (businessObjectFormatEntity.getRetentionType() != null) {
            // Create a retention expiration predicate for this business object format.
            Predicate businessObjectFormatRetentionExpirationPredicate = null;

            if (StringUtils.equals(businessObjectFormatEntity.getRetentionType().getCode(),
                    RetentionTypeEntity.BDATA_RETENTION_DATE)) {
                // Select business object data that has expired per its explicitly configured retention expiration date.
                businessObjectFormatRetentionExpirationPredicate = builder.lessThan(
                        businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.retentionExpiration),
                        currentTimestamp);
            } else if (StringUtils.equals(businessObjectFormatEntity.getRetentionType().getCode(),
                    RetentionTypeEntity.PARTITION_VALUE)
                    && businessObjectFormatEntity.getRetentionPeriodInDays() != null) {
                // Compute the retention expiration date and convert it to the date format to match against partition values.
                String retentionExpirationDate = DateFormatUtils.format(
                        DateUtils.addDays(new Date(),
                                -1 * businessObjectFormatEntity.getRetentionPeriodInDays()),
                        DEFAULT_SINGLE_DAY_DATE_MASK);

                // Create a predicate to compare business object data primary partition value against the retention expiration date.
                businessObjectFormatRetentionExpirationPredicate = builder.lessThan(
                        businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.partitionValue),
                        retentionExpirationDate);
            }

            // If it was initialize, complete processing of retention expiration predicate for this business object format.
            if (businessObjectFormatRetentionExpirationPredicate != null) {
                // Update the predicate to match this business object format w/o version.
                businessObjectFormatRetentionExpirationPredicate = builder.and(
                        businessObjectFormatRetentionExpirationPredicate,
                        builder.equal(
                                builder.upper(
                                        businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                                businessObjectFormatEntity.getUsage().toUpperCase()));
                businessObjectFormatRetentionExpirationPredicate = builder.and(
                        businessObjectFormatRetentionExpirationPredicate,
                        builder.equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.fileType),
                                businessObjectFormatEntity.getFileType()));

                // Add this business object format specific retention expiration predicate to other
                // retention expiration predicates created for the specified business object definition.
                if (businessObjectDefinitionRetentionExpirationPredicate == null) {
                    businessObjectDefinitionRetentionExpirationPredicate = businessObjectFormatRetentionExpirationPredicate;
                } else {
                    businessObjectDefinitionRetentionExpirationPredicate = builder.or(
                            businessObjectDefinitionRetentionExpirationPredicate,
                            businessObjectFormatRetentionExpirationPredicate);
                }
            }
        }
    }

    // Fail if no retention expiration predicates got created per specified business objject definition.
    Assert.notNull(businessObjectDefinitionRetentionExpirationPredicate, String.format(
            "Business object definition with name \"%s\" and namespace \"%s\" has no business object formats with supported retention type.",
            businessObjectDefinitionKey.getBusinessObjectDefinitionName(),
            businessObjectDefinitionKey.getNamespace()));

    // Add created business object definition retention expiration predicate to the main query predicate passed to this method and return the result.
    return builder.and(mainQueryPredicate, businessObjectDefinitionRetentionExpirationPredicate);
}

From source file:org.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java

/**
 * Apply a predicate for registration date range filter.
 *
 * @param registrationDateRangeFilter the registration date range filter, not null
 * @param businessObjectDataEntity the business object data entity
 * @param builder the query builder//from w w  w .j  a  va  2s  .co m
 * @param predicate the predicate to be updated
 *
 * @return the predicate with added registration date range filter
 */
private Predicate applyRegistrationDateRangeFilter(RegistrationDateRangeFilter registrationDateRangeFilter,
        Root<BusinessObjectDataEntity> businessObjectDataEntity, CriteriaBuilder builder, Predicate predicate) {
    // Apply predicate for registration start date and removed the time portion of the date.
    if (registrationDateRangeFilter.getStartRegistrationDate() != null) {
        predicate = builder.and(predicate, builder.greaterThanOrEqualTo(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn),
                HerdDateUtils.resetTimeToMidnight(registrationDateRangeFilter.getStartRegistrationDate())));
    }

    // Apply predicate for registration end date. Removed time portion of the date and added one day to get the result till the end of the day
    if (registrationDateRangeFilter.getEndRegistrationDate() != null) {
        predicate = builder.and(predicate, builder.lessThan(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn),
                HerdDateUtils.addDays(
                        HerdDateUtils.resetTimeToMidnight(registrationDateRangeFilter.getEndRegistrationDate()),
                        1)));
    }

    return predicate;
}

From source file:org.finra.herd.dao.impl.BusinessObjectFormatDaoImpl.java

@Override
public Long getBusinessObjectFormatCountByPartitionKeys(String namespace, String businessObjectDefinitionName,
        String businessObjectFormatUsage, String businessObjectFormatFileType,
        Integer businessObjectFormatVersion, List<String> partitionKeys) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);

    // The criteria root is the business object format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntityRoot = criteria
            .from(BusinessObjectFormatEntity.class);

    // Create path.
    Expression<Long> businessObjectFormatRecordCount = builder.count(businessObjectFormatEntityRoot);

    // Namespace is a required parameter, so fetch the relative entity to optimize the main query.
    NamespaceEntity namespaceEntity = namespaceDao.getNamespaceByCd(namespace);

    // If specified namespace does not exist, then return a zero record count.
    if (namespaceEntity == null) {
        return 0L;
    }//from w ww. j  a  v a2s. co m

    // If file type is specified, fetch the relative entity to optimize the main query.
    FileTypeEntity fileTypeEntity = null;
    if (StringUtils.isNotBlank(businessObjectFormatFileType)) {
        fileTypeEntity = fileTypeDao.getFileTypeByCode(businessObjectFormatFileType);

        // If specified file type does not exist, then return a zero record count.
        if (fileTypeEntity == null) {
            return 0L;
        }
    }

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntityRoot
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);

    // Create main query restrictions based on the specified parameters.
    List<Predicate> predicates = new ArrayList<>();

    // Create restriction on namespace code and business object definition name.
    predicates.add(builder.equal(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.namespace),
            namespaceEntity));
    predicates.add(builder.equal(
            builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
            businessObjectDefinitionName.toUpperCase()));

    // If specified, create restriction on business object format usage.
    if (!StringUtils.isEmpty(businessObjectFormatUsage)) {
        predicates.add(builder.equal(
                builder.upper(businessObjectFormatEntityRoot.get(BusinessObjectFormatEntity_.usage)),
                businessObjectFormatUsage.toUpperCase()));
    }

    // If specified, create restriction on business object format file type.
    if (fileTypeEntity != null) {
        predicates
                .add(builder.equal(businessObjectFormatEntityRoot.get(BusinessObjectFormatEntity_.fileTypeCode),
                        fileTypeEntity.getCode()));
    }

    // If specified, create restriction on business object format version.
    if (businessObjectFormatVersion != null) {
        predicates.add(builder.equal(
                businessObjectFormatEntityRoot.get(BusinessObjectFormatEntity_.businessObjectFormatVersion),
                businessObjectFormatVersion));
    }

    // If specified, create restriction on partition keys.
    if (CollectionUtils.isNotEmpty(partitionKeys)) {
        for (String partitionKey : partitionKeys) {
            // Add restriction on partition key (partition column).
            // Partition key must identify a partition column that is at partition level that could be explicitly registered.
            // Partition level uses one-based numbering.
            Join<BusinessObjectFormatEntity, SchemaColumnEntity> schemaColumnEntityJoin = businessObjectFormatEntityRoot
                    .join(BusinessObjectFormatEntity_.schemaColumns);
            predicates.add(builder.equal(builder.upper(schemaColumnEntityJoin.get(SchemaColumnEntity_.name)),
                    partitionKey.toUpperCase()));
            predicates.add(builder.isNotNull(schemaColumnEntityJoin.get(SchemaColumnEntity_.partitionLevel)));
            predicates.add(builder.lessThan(schemaColumnEntityJoin.get(SchemaColumnEntity_.partitionLevel),
                    BusinessObjectDataEntity.MAX_SUBPARTITIONS + 2));
        }
    }

    // Add all clauses for the query.
    criteria.select(businessObjectFormatRecordCount)
            .where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).distinct(true);

    // Execute the query and return the result.
    return entityManager.createQuery(criteria).getSingleResult();
}

From source file:org.finra.herd.dao.impl.StorageUnitDaoImpl.java

@Override
public List<StorageUnitEntity> getS3StorageUnitsToCleanup(int maxResult) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<StorageUnitEntity> criteria = builder.createQuery(StorageUnitEntity.class);

    // The criteria root is the storage unit.
    Root<StorageUnitEntity> storageUnitEntityRoot = criteria.from(StorageUnitEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageUnitEntity, StorageEntity> storageEntityJoin = storageUnitEntityRoot
            .join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntityJoin = storageEntityJoin
            .join(StorageEntity_.storagePlatform);
    Join<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntityJoin = storageUnitEntityRoot
            .join(StorageUnitEntity_.status);
    Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntityJoin = storageUnitEntityRoot
            .join(StorageUnitEntity_.businessObjectData);
    Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity = businessObjectDataEntityJoin
            .join(BusinessObjectDataEntity_.status);

    // Get the current time.
    Timestamp currentTime = new Timestamp(System.currentTimeMillis());

    // Create the standard restrictions (i.e. the standard where clauses).
    // Restrictions include:
    //      - Storage platform is set to S3 storage
    //      - Storage unit status is DISABLED
    //      - Associated BData has a DELETED status
    //      - Final destroy on timestamp < current time
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(builder.equal(storagePlatformEntityJoin.get(StoragePlatformEntity_.name),
            StoragePlatformEntity.S3));//from ww  w. j  a  v a2s.  c  om
    predicates.add(builder.equal(storageUnitStatusEntityJoin.get(StorageUnitStatusEntity_.code),
            StorageUnitStatusEntity.DISABLED));
    predicates.add(builder.equal(businessObjectDataStatusEntity.get(BusinessObjectDataStatusEntity_.code),
            BusinessObjectDataStatusEntity.DELETED));
    predicates.add(builder.lessThan(storageUnitEntityRoot.get(StorageUnitEntity_.finalDestroyOn), currentTime));

    // Order the results.
    Order orderBy = builder.asc(storageUnitEntityRoot.get(StorageUnitEntity_.finalDestroyOn));

    // Add the clauses for the query.
    criteria.select(storageUnitEntityRoot)
            .where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).orderBy(orderBy);

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

From source file:org.finra.herd.dao.impl.StorageUnitDaoImpl.java

@Override
public List<StorageUnitEntity> getS3StorageUnitsToExpire(int maxResult) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<StorageUnitEntity> criteria = builder.createQuery(StorageUnitEntity.class);

    // The criteria root is the storage unit.
    Root<StorageUnitEntity> storageUnitEntityRoot = criteria.from(StorageUnitEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageUnitEntity, StorageEntity> storageEntityJoin = storageUnitEntityRoot
            .join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntityJoin = storageEntityJoin
            .join(StorageEntity_.storagePlatform);
    Join<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntityJoin = storageUnitEntityRoot
            .join(StorageUnitEntity_.status);

    // Get the current time.
    Timestamp currentTime = new Timestamp(System.currentTimeMillis());

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(builder.equal(storagePlatformEntityJoin.get(StoragePlatformEntity_.name),
            StoragePlatformEntity.S3));//w ww .j a v a  2 s. co m
    predicates.add(builder.equal(storageUnitStatusEntityJoin.get(StorageUnitStatusEntity_.code),
            StorageUnitStatusEntity.RESTORED));
    predicates.add(
            builder.lessThan(storageUnitEntityRoot.get(StorageUnitEntity_.restoreExpirationOn), currentTime));

    // Order the results.
    Order orderBy = builder.asc(storageUnitEntityRoot.get(StorageUnitEntity_.restoreExpirationOn));

    // Add the clauses for the query.
    criteria.select(storageUnitEntityRoot)
            .where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).orderBy(orderBy);

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

From source file:org.jasig.portal.events.aggr.JpaBaseAggregationDao.java

@Override
public final void afterPropertiesSet() throws Exception {
    this.timeDimensionParameter = this.createParameterExpression(TimeDimension.class, "timeDimension");
    this.dateDimensionParameter = this.createParameterExpression(DateDimension.class, "dateDimension");
    this.intervalParameter = this.createParameterExpression(AggregationInterval.class, "interval");
    this.aggregatedGroupParameter = this.createParameterExpression(AggregatedGroupMapping.class,
            "aggregatedGroup");
    this.aggregatedGroupsParameter = this.createParameterExpression(Set.class, "aggregatedGroups");
    this.startDate = this.createParameterExpression(LocalDate.class, "startDate");
    this.endMinusOneDate = this.createParameterExpression(LocalDate.class, "endMinusOneDate");
    this.endDate = this.createParameterExpression(LocalDate.class, "endDate");
    this.startTime = this.createParameterExpression(LocalTime.class, "startTime");
    this.endTime = this.createParameterExpression(LocalTime.class, "endTime");
    this.createParameterExpressions();

    this.findAggregationByDateTimeIntervalQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override/*w  w w  .  j a  v a 2  s  . c  om*/
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);

                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);

                    addFetches(ba);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(
                            cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter),
                            cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter),
                            cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));

                    return criteriaQuery;
                }
            });

    this.findAggregationByDateTimeIntervalGroupQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);
                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);

                    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
                    keyPredicates
                            .add(cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter));
                    keyPredicates
                            .add(cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter));
                    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
                    keyPredicates.add(
                            cb.equal(ba.get(BaseAggregationImpl_.aggregatedGroup), aggregatedGroupParameter));
                    addAggregationSpecificKeyPredicate(cb, ba, keyPredicates);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));

                    return criteriaQuery;
                }
            });

    this.findAggregationsByDateRangeQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);

                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);
                    final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension,
                            JoinType.LEFT);
                    final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension,
                            JoinType.LEFT);

                    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
                    keyPredicates.add(cb.and( //Restrict results by outer date range
                            cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate),
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endDate)));
                    keyPredicates.add(cb.or( //Restrict start of range by time as well
                            cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate),
                            cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime)));
                    keyPredicates.add(cb.or( //Restrict end of range by time as well
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate),
                            cb.lessThan(td.get(TimeDimensionImpl_.time), endTime)));
                    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
                    keyPredicates
                            .add(ba.get(BaseAggregationImpl_.aggregatedGroup).in(aggregatedGroupsParameter));
                    addAggregationSpecificKeyPredicate(cb, ba, keyPredicates);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));
                    criteriaQuery.orderBy(cb.desc(dd.get(DateDimensionImpl_.date)),
                            cb.desc(td.get(TimeDimensionImpl_.time)));

                    return criteriaQuery;
                }
            });

    /*
     * Similar to the previous query but only returns aggregates that also match the unclosed predicate generated
     * by the subclass. This is used for finding aggregates that missed having intervalComplete called due to
     * interval boundary placement.
     */
    this.findUnclosedAggregationsByDateRangeQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);

                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);
                    final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension,
                            JoinType.LEFT);
                    final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension,
                            JoinType.LEFT);

                    addFetches(ba);

                    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
                    keyPredicates.add(cb.and( //Restrict results by outer date range
                            cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate),
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endDate)));
                    keyPredicates.add(cb.or( //Restrict start of range by time as well
                            cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate),
                            cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime)));
                    keyPredicates.add(cb.or( //Restrict end of range by time as well
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate),
                            cb.lessThan(td.get(TimeDimensionImpl_.time), endTime)));
                    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
                    //No aggregation specific key bits here, we only have start/end/interval parameters to work with
                    addUnclosedPredicate(cb, ba, keyPredicates);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));

                    return criteriaQuery;
                }
            });

    this.createCriteriaQueries();
}