Example usage for javax.persistence.criteria CriteriaBuilder lessThanOrEqualTo

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletCookieDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.nowParameter = this.createParameterExpression(DateTime.class, "now");

    this.deletePortalCookieQueryString = "DELETE FROM " + PortalCookieImpl.class.getName() + " e " + "WHERE e."
            + PortalCookieImpl_.expires.getName() + " <= :" + this.nowParameter.getName();

    this.deleteEmptyPortalCookieQueryString = "DELETE FROM " + PortalCookieImpl.class.getName() + " e "
            + "WHERE e." + PortalCookieImpl_.expires.getName() + " <= :" + this.nowParameter.getName() + " AND "
            + "e." + PortalCookieImpl_.portletCookies.getName() + " IS EMPTY";

    this.deletePortletCookieQueryString = "DELETE FROM " + PortletCookieImpl.class.getName() + " e "
            + "WHERE e." + PortletCookieImpl_.expires.getName() + " <= :" + this.nowParameter.getName();

    this.findExpiredByParentPortletCookiesQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletCookieImpl>>() {
                @Override/*from   w  w  w. ja  v  a  2s. c o  m*/
                public CriteriaQuery<PortletCookieImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<PortletCookieImpl> criteriaQuery = cb
                            .createQuery(PortletCookieImpl.class);
                    final Root<PortletCookieImpl> typeRoot = criteriaQuery.from(PortletCookieImpl.class);
                    criteriaQuery.select(typeRoot);
                    criteriaQuery.where(cb.lessThanOrEqualTo(
                            typeRoot.get(PortletCookieImpl_.portalCookie).get(PortalCookieImpl_.expires),
                            nowParameter));

                    return criteriaQuery;
                }
            });
}

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

/**
 * {@inheritDoc}//from   w  w  w  .ja v a2s .c  om
 */
@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 ww .  ja v  a 2 s .c om
 */
@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.//w w w. jav  a2  s. 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

/**
 * {@inheritDoc}/*ww w .  ja v a 2 s.  c  o  m*/
 */
@Override
public List<BusinessObjectDataEntity> getBusinessObjectDataFromStorageOlderThan(String storageName,
        int thresholdMinutes, List<String> businessObjectDataStatusesToIgnore) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataEntity> criteria = builder.createQuery(BusinessObjectDataEntity.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, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.status);

    // Compute threshold timestamp based on the current database timestamp and threshold minutes.
    Timestamp thresholdTimestamp = subtractMinutes(getCurrentTimestamp(), thresholdMinutes);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageName.toUpperCase());
    queryRestriction = builder.and(queryRestriction, builder.not(businessObjectDataStatusEntity
            .get(BusinessObjectDataStatusEntity_.code).in(businessObjectDataStatusesToIgnore)));
    queryRestriction = builder.and(queryRestriction, builder.lessThanOrEqualTo(
            businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn), thresholdTimestamp));

    // Order the results by file path.
    Order orderByCreatedOn = builder.asc(businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn));

    // Add the clauses for the query.
    criteria.select(businessObjectDataEntity).where(queryRestriction).orderBy(orderByCreatedOn);

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

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//from  w w w.  j ava2s  . 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//ww w  . j a v a 2s .c om
 *
 * @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//from w  ww.  j  a  v a 2  s.  c  o  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;
}

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

/**
 * TODO: Remove this method once we migrate away from Oracle getStorageUploadStatsByBusinessObjectDefinition that uses Oracle specific 'trunc' function.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range//from  w w w  . j a  va2  s  .  co m
 *
 * @return the upload statistics
 */
private StorageBusinessObjectDefinitionDailyUploadStats getStorageUploadStatsByBusinessObjectDefinitionOracle(
        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);
    Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntity = storageUnitEntity
            .join(StorageUnitEntity_.businessObjectData);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, DataProviderEntity> dataProviderEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.dataProvider);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Create paths and expressions.
    Path<String> namespacePath = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> dataProviderNamePath = dataProviderEntity.get(DataProviderEntity_.name);
    Path<String> businessObjectDefinitionNamePath = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    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, namespacePath, dataProviderNamePath,
            businessObjectDefinitionNamePath, totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

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

    grouping.add(truncCreatedOnDateExpression);
    grouping.add(namespacePath);
    grouping.add(dataProviderNamePath);
    grouping.add(businessObjectDefinitionNamePath);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(truncCreatedOnDateExpression), builder.asc(namespacePath),
            builder.asc(dataProviderNamePath), builder.asc(businessObjectDefinitionNamePath));

    // 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(truncCreatedOnDateExpression)));
        uploadStat.setNamespace(tuple.get(namespacePath));
        uploadStat.setDataProviderName(tuple.get(dataProviderNamePath));
        uploadStat.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNamePath));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

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

@Override
public List<BusinessObjectDataEntity> getBusinessObjectDataFromStorageOlderThan(StorageEntity storageEntity,
        int thresholdMinutes, List<String> businessObjectDataStatuses) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataEntity> criteria = builder.createQuery(BusinessObjectDataEntity.class);

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

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

    // Compute threshold timestamp based on the current database timestamp and threshold minutes.
    Timestamp thresholdTimestamp = HerdDateUtils.addMinutes(getCurrentTimestamp(), -thresholdMinutes);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(/*from   w w  w .j  a v a 2 s . com*/
            builder.equal(storageUnitEntityJoin.get(StorageUnitEntity_.storageName), storageEntity.getName()));
    predicates.add(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.statusCode)
            .in(businessObjectDataStatuses));
    predicates.add(builder.lessThanOrEqualTo(
            businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.createdOn), thresholdTimestamp));

    // Order results by "created on" timestamp.
    Order orderBy = builder.asc(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.createdOn));

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

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