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.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java

/**
 * Retrieves partition value per specified parameters that includes the aggregate function.
 * <p>//from   w w w .  j av  a2  s .c om
 * Returns null if the business object format key does not exist.
 *
 * @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 based on
 * the specified business object data status will be used for each partition value.
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified.
 * @param storageNames the optional list of storage names (case-insensitive)
 * @param storagePlatformType the optional storage platform type, e.g. S3 for Hive DDL. It is ignored when the list of storages is not empty
 * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storages is not empty or
 * the storage platform type is specified
 * @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,
        final BusinessObjectFormatKey businessObjectFormatKey, final Integer businessObjectDataVersion,
        String businessObjectDataStatus, List<String> storageNames, String storagePlatformType,
        String excludedStoragePlatformType, final AggregateFunction aggregateFunction,
        String upperBoundPartitionValue, String lowerBoundPartitionValue) {
    // We cannot use businessObjectFormatKey passed in since it is case-insensitive. Case-insensitive values requires upper() function in the SQL query, and
    // it has caused performance problems. So we need to extract case-sensitive business object format key from database so we can eliminate the upper()
    // function.
    BusinessObjectFormatEntity businessObjectFormatEntity = businessObjectFormatDao
            .getBusinessObjectFormatByAltKey(businessObjectFormatKey);

    BusinessObjectFormatKey businessObjectFormatKeyCaseSensitive = (BusinessObjectFormatKey) businessObjectFormatKey
            .clone();
    if (businessObjectFormatEntity == null) {
        // Returns null if business object format key does not exist.
        return null;
    } else {
        // Sets the exact values for business object format key from the database. Note that usage type is still case-insensitive.
        businessObjectFormatKeyCaseSensitive.setNamespace(
                businessObjectFormatEntity.getBusinessObjectDefinition().getNamespace().getCode());
        businessObjectFormatKeyCaseSensitive.setBusinessObjectDefinitionName(
                businessObjectFormatEntity.getBusinessObjectDefinition().getName());
        businessObjectFormatKeyCaseSensitive
                .setBusinessObjectFormatFileType(businessObjectFormatEntity.getFileType().getCode());
    }

    // 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> businessObjectDataEntityRoot = criteria.from(BusinessObjectDataEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntityJoin = businessObjectFormatEntityJoin
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntityJoin = businessObjectFormatEntityJoin
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntityJoin = businessObjectDefinitionEntityJoin
            .join(BusinessObjectDefinitionEntity_.namespace);
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntityJoin = storageUnitEntityJoin
            .join(StorageUnitEntity_.status);
    Join<StorageUnitEntity, StorageEntity> storageEntityJoin = storageUnitEntityJoin
            .join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntityJoin = storageEntityJoin
            .join(StorageEntity_.storagePlatform);

    // Create the path.
    Expression<String> partitionValue;
    SingularAttribute<BusinessObjectDataEntity, String> singleValuedAttribute = BUSINESS_OBJECT_DATA_PARTITIONS
            .get(partitionColumnPosition - 1);
    switch (aggregateFunction) {
    case GREATEST:
        partitionValue = builder.greatest(businessObjectDataEntityRoot.get(singleValuedAttribute));
        break;
    case LEAST:
        partitionValue = builder.least(businessObjectDataEntityRoot.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(namespaceEntityJoin.get(NamespaceEntity_.code),
            businessObjectFormatKeyCaseSensitive.getNamespace());
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(businessObjectDefinitionEntityJoin.get(BusinessObjectDefinitionEntity_.name),
                    businessObjectFormatKeyCaseSensitive.getBusinessObjectDefinitionName()));
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(builder.upper(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                    businessObjectFormatKeyCaseSensitive.getBusinessObjectFormatUsage().toUpperCase()));
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(fileTypeEntityJoin.get(FileTypeEntity_.code),
                    businessObjectFormatKeyCaseSensitive.getBusinessObjectFormatFileType()));

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

    // If a data version was specified, use it.
    if (businessObjectDataVersion != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.equal(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.version),
                        businessObjectDataVersion));
    }
    // Business object data version is not specified, so get the latest one as per specified business object data status in the specified storage.
    else {
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntityRoot, businessObjectFormatEntityJoin, businessObjectDataStatus,
                storageNames, storagePlatformType, excludedStoragePlatformType, false);

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

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

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

    // If specified, add restriction on storage.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            getQueryRestrictionOnStorage(builder, storageEntityJoin, storagePlatformEntityJoin, storageNames,
                    storagePlatformType, excludedStoragePlatformType));

    // Search across only "available" storage units.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.isTrue(storageUnitStatusEntityJoin.get(StorageUnitStatusEntity_.available)));

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

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

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

/**
 * Creates a predicate for partition value filters.
 *
 * @param businessDataSearchKey businessDataSearchKey
 * @param businessObjectDataEntity businessObjectDataEntity
 * @param businessObjectFormatEntity businessObjectFormatEntity
 * @param builder builder/*w w w  .  jav a 2  s  .  co m*/
 * @param predicatePram predicate parameter
 *
 * @return the predicate
 */
private Predicate createPartitionValueFilters(BusinessObjectDataSearchKey businessDataSearchKey,
        Root<BusinessObjectDataEntity> businessObjectDataEntity,
        Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity,
        CriteriaBuilder builder, Predicate predicatePram) {
    Predicate predicate = predicatePram;

    if (businessDataSearchKey.getPartitionValueFilters() != null
            && !businessDataSearchKey.getPartitionValueFilters().isEmpty()) {
        for (PartitionValueFilter partitionFilter : businessDataSearchKey.getPartitionValueFilters()) {
            Join<BusinessObjectFormatEntity, SchemaColumnEntity> schemaEntity = businessObjectFormatEntity
                    .join(BusinessObjectFormatEntity_.schemaColumns);

            List<String> partitionValues = partitionFilter.getPartitionValues();

            predicate = builder.and(predicate,
                    builder.equal(builder.upper(schemaEntity.get(SchemaColumnEntity_.name)),
                            partitionFilter.getPartitionKey().toUpperCase()));
            predicate = builder.and(predicate,
                    builder.isNotNull(schemaEntity.get(SchemaColumnEntity_.partitionLevel)));

            if (partitionValues != null && !partitionValues.isEmpty()) {
                predicate = builder.and(predicate, builder.or(
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 1),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 2),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 3),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 4),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 5),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5)
                                        .in(partitionValues))));
            } else if (partitionFilter.getPartitionValueRange() != null) {
                PartitionValueRange partitionRange = partitionFilter.getPartitionValueRange();
                String startPartitionValue = partitionRange.getStartPartitionValue();
                String endPartitionValue = partitionRange.getEndPartitionValue();

                predicate = builder.and(predicate, builder.or(
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 1),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 2),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 3),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 4),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 5),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5),
                                        endPartitionValue))));
            }
        }
    }

    return predicate;
}

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

@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 {/*from  w  w  w . ja  v a  2 s . c o  m*/
        // 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.herd.dao.impl.ExpectedPartitionValueDaoImpl.java

@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()));
        }/*from  w  w w . ja v a  2 s.c o m*/

        // 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.herd.dao.impl.HerdDaoImpl.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 based on
 * the specified business object data status will be used for each partition value.
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified.
 * @param storageNames the list of storages (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//from   w  ww.j  av a2 s .  c om
 */
private String getBusinessObjectDataPartitionValue(int partitionColumnPosition,
        BusinessObjectFormatKey businessObjectFormatKey, Integer businessObjectDataVersion,
        String businessObjectDataStatus, List<String> storageNames, 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.
    if (businessObjectDataVersion != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.equal(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.version), businessObjectDataVersion));
    }
    // Business object data version is not specified, so get the latest one as per specified business object data status in the specified storage.
    else {
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntity, businessObjectFormatEntity, businessObjectDataStatus, 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 main query where clause.
    List<String> uppercaseStorageNames = new ArrayList<>();
    for (String storageName : storageNames) {
        uppercaseStorageNames.add(storageName.toUpperCase());
    }
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.upper(storageEntity.get(StorageEntity_.name)).in(uppercaseStorageNames));

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

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

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

/**
 * {@inheritDoc}/*from   w  w  w. j a  v a2s  .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 = HerdDateUtils.addMinutes(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.herd.dao.impl.HerdDaoImpl.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  av  a 2  s. co 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(HerdDateUtils.getXMLGregorianCalendarValue(tuple.get(createdDate)));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

From source file:org.finra.herd.dao.impl.HerdDaoImpl.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/* w  w  w .j  a v a2s  . 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(
                HerdDateUtils.getXMLGregorianCalendarValue(tuple.get(truncCreatedOnDateExpression)));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

From source file:org.finra.herd.dao.impl.HerdDaoImpl.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 va2s. 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(HerdDateUtils.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.herd.dao.impl.HerdDaoImpl.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//  w w  w .  jav a 2  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(
                HerdDateUtils.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;
}