Example usage for javax.persistence.criteria CriteriaBuilder in

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

Introduction

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

Prototype

<T> In<T> in(Expression<? extends T> expression);

Source Link

Document

Create predicate to test whether given expression is contained in a list of values.

Usage

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//  w  w  w  . j  av a 2  s .  c o m
 */
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

/**
 * Retrieves a list of storage unit entities per specified parameters. This method processes a sublist of partition filters specified by
 * partitionFilterSubListFromIndex and partitionFilterSubListSize parameters.
 *
 * @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 partitionFilters the list of partition filter to be used to select business object data instances. Each partition filter contains a list of
 * primary and sub-partition values in the right order up to the maximum partition levels allowed by business object data registration - with partition
 * values for the relative partitions not to be used for selection passed as nulls
 * @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 is returned
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified. When
 * business object data version and business object data status both are not specified, the latest data version for each set of partition values will be
 * used regardless of the status//from  www  . j a va2  s .com
 * @param storageNames the list of storage names where the business object data storage units should be looked for (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 partitionFilterSubListFromIndex the index of the first element in the partition filter sublist
 * @param partitionFilterSubListSize the size of the partition filter sublist
 * @param selectOnlyAvailableStorageUnits specifies if only available storage units will be selected or any storage units regardless of their status
 *
 * @return the list of storage unit entities sorted by partition values
 */
private List<StorageUnitEntity> getStorageUnitsByPartitionFiltersAndStorages(
        BusinessObjectFormatKey businessObjectFormatKey, List<List<String>> partitionFilters,
        Integer businessObjectDataVersion, String businessObjectDataStatus, List<String> storageNames,
        String storagePlatformType, String excludedStoragePlatformType, boolean selectOnlyAvailableStorageUnits,
        int partitionFilterSubListFromIndex, int partitionFilterSubListSize) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

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

    // Join to the other tables we can filter on.
    Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntity = storageUnitEntity
            .join(StorageUnitEntity_.businessObjectData);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntity = storageEntity
            .join(StorageEntity_.storagePlatform);
    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<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntity = storageUnitEntity
            .join(StorageUnitEntity_.status);

    // Create the standard restrictions (i.e. the standard where clauses).

    // Create a standard restriction based on the business object format key values.
    // Please note that we specify not to ignore the business object format version.
    Predicate mainQueryRestriction = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity,
            businessObjectDefinitionEntity, businessObjectFormatKey, false);

    // If a format version was not specified, use the latest available for this set of partition values.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) {
        // Get the latest available format version for this set of partition values and per other restrictions.
        Subquery<Integer> subQuery = getMaximumBusinessObjectFormatVersionSubQuery(builder, criteria,
                businessObjectDefinitionEntity, businessObjectFormatEntity, fileTypeEntity,
                businessObjectDataEntity, businessObjectDataVersion, businessObjectDataStatus, storageEntity,
                selectOnlyAvailableStorageUnits);

        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.in(
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion))
                        .value(subQuery));
    }

    // Add restriction as per specified primary and/or sub-partition values.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            getQueryRestrictionOnPartitionValues(builder, businessObjectDataEntity,
                    partitionFilters.subList(partitionFilterSubListFromIndex,
                            partitionFilterSubListFromIndex + partitionFilterSubListSize)));

    // If a data version was specified, use it. Otherwise, use the latest one as per specified business object data status.
    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 as per specified business object data status, if any.
        // Meaning, when both business object data version and business object data status are not specified, we just return
        // the latest business object data version in the specified storage.
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntity, businessObjectFormatEntity, businessObjectDataStatus, storageEntity);

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

    // If specified, add restriction on storage.
    if (!CollectionUtils.isEmpty(storageNames)) {
        // 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));
    } else if (StringUtils.isNotBlank(storagePlatformType)) {
        // Select storage units only from the storages of the specified storage platform type.
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.equal(storagePlatformEntity.get(StoragePlatformEntity_.name), storagePlatformType));
    } else if (StringUtils.isNotBlank(excludedStoragePlatformType)) {
        // Ignore any storages of the excluded storage platform type.
        mainQueryRestriction = builder.and(mainQueryRestriction, builder
                .notEqual(storagePlatformEntity.get(StoragePlatformEntity_.name), excludedStoragePlatformType));
    }

    // If specified, add a restriction on storage unit status availability flag.
    if (selectOnlyAvailableStorageUnits) {
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.isTrue(storageUnitStatusEntity.get(StorageUnitStatusEntity_.available)));
    }

    // Order by partitions and storage names.
    List<Order> orderBy = new ArrayList<>();
    for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartition : BUSINESS_OBJECT_DATA_PARTITIONS) {
        orderBy.add(builder.asc(businessObjectDataEntity.get(businessObjectDataPartition)));
    }
    orderBy.add(builder.asc(storageEntity.get(StorageEntity_.name)));

    // Add the clauses for the query.
    // Please note that we use multiselect here in order to eliminate the Hibernate N+1 SELECT's problem,
    // happening when we select storage unit entities and access their relative business object data entities.
    // This is an alternative approach, since adding @Fetch(FetchMode.JOIN) failed to address the issue.
    criteria.multiselect(storageUnitEntity, storageUnitStatusEntity, storageEntity, storagePlatformEntity,
            businessObjectDataEntity, businessObjectFormatEntity).where(mainQueryRestriction).orderBy(orderBy);

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

    // Build a list of storage unit entities to return.
    List<StorageUnitEntity> storageUnitEntities = new ArrayList<>();
    for (Tuple tuple : tuples) {
        storageUnitEntities.add(tuple.get(storageUnitEntity));
    }

    return storageUnitEntities;
}

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

/**
 * Retrieves a list of storage unit availability DTOs per specified parameters. This method processes a sublist of partition filters specified by
 * partitionFilterSubListFromIndex and partitionFilterSubListSize parameters.
 *
 * @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 partitionFilters the list of partition filter to be used to select business object data instances. Each partition filter contains a list of
 * primary and sub-partition values in the right order up to the maximum partition levels allowed by business object data registration - with partition
 * values for the relative partitions not to be used for selection passed as nulls
 * @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 is returned
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified. When
 * business object data version and business object data status both are not specified, the latest data version for each set of partition values will be
 * used regardless of the status/*from w ww .j  a  v a2 s  . c  o m*/
 * @param storageNames the list of storage names where the business object data storage units should be looked for (case-insensitive)
 * @param storagePlatformType the optional storage platform type, e.g. S3 for Hive DDL. It is ignored when the list of storage names is not empty
 * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storage names is not
 * empty or the storage platform type is specified
 * @param partitionFilterSubListFromIndex the index of the first element in the partition filter sublist
 * @param partitionFilterSubListSize the size of the partition filter sublist
 * @param selectOnlyAvailableStorageUnits specifies if only available storage units will be selected or any storage units regardless of their status
 *
 * @return the list of storage unit availability DTOs sorted by partition values
 */
private List<StorageUnitAvailabilityDto> getStorageUnitsByPartitionFilters(
        BusinessObjectFormatKey businessObjectFormatKey, List<List<String>> partitionFilters,
        Integer businessObjectDataVersion, String businessObjectDataStatus, List<String> storageNames,
        String storagePlatformType, String excludedStoragePlatformType, boolean selectOnlyAvailableStorageUnits,
        int partitionFilterSubListFromIndex, int partitionFilterSubListSize) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

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

    // Join to the other tables we can filter on.
    Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntity = storageUnitEntity
            .join(StorageUnitEntity_.businessObjectData);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntity = storageEntity
            .join(StorageEntity_.storagePlatform);
    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<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntity = storageUnitEntity
            .join(StorageUnitEntity_.status);

    // Create the standard restrictions (i.e. the standard where clauses).

    // Create a standard restriction based on the business object format key values.
    // Please note that we specify not to ignore the business object format version.
    Predicate mainQueryRestriction = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity,
            businessObjectDefinitionEntity, namespaceEntity, businessObjectFormatKey, false);

    // If a format version was not specified, use the latest available for this set of partition values.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) {
        // Get the latest available format version for this set of partition values and per other restrictions.
        Subquery<Integer> subQuery = getMaximumBusinessObjectFormatVersionSubQuery(builder, criteria,
                businessObjectDefinitionEntity, businessObjectFormatEntity, fileTypeEntity,
                businessObjectDataEntity, businessObjectDataVersion, businessObjectDataStatus, storageNames,
                storagePlatformType, excludedStoragePlatformType, selectOnlyAvailableStorageUnits);

        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.in(
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion))
                        .value(subQuery));
    }

    // Add restriction as per specified primary and/or sub-partition values.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            getQueryRestrictionOnPartitionValues(builder, businessObjectDataEntity,
                    partitionFilters.subList(partitionFilterSubListFromIndex,
                            partitionFilterSubListFromIndex + partitionFilterSubListSize)));

    // If a data version was specified, use it. Otherwise, use the latest one as per specified business object data status.
    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 as per specified business object data status, if any.
        // Meaning, when both business object data version and business object data status are not specified, we just return
        // the latest business object data version in the specified storage.
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntity, businessObjectFormatEntity, businessObjectDataStatus, storageNames,
                storagePlatformType, excludedStoragePlatformType, selectOnlyAvailableStorageUnits);

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

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

    // If specified, add a restriction on storage unit status availability flag.
    if (selectOnlyAvailableStorageUnits) {
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.isTrue(storageUnitStatusEntity.get(StorageUnitStatusEntity_.available)));
    }

    // Order by partitions and storage names.
    List<Order> orderBy = new ArrayList<>();
    for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartition : BUSINESS_OBJECT_DATA_PARTITIONS) {
        orderBy.add(builder.asc(businessObjectDataEntity.get(businessObjectDataPartition)));
    }
    orderBy.add(builder.asc(storageEntity.get(StorageEntity_.name)));

    // Get the columns.
    Path<Integer> storageUnitIdColumn = storageUnitEntity.get(StorageUnitEntity_.id);
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Path<String> primaryPartitionValueColumn = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue);
    Path<String> subPartitionValue1Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue2);
    Path<String> subPartitionValue2Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue3);
    Path<String> subPartitionValue3Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue4);
    Path<String> subPartitionValue4Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue5);
    Path<Integer> businessObjectDataVersionColumn = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.version);
    Path<String> storageNameColumn = storageEntity.get(StorageEntity_.name);
    Path<String> storageUnitDirectoryPathColumn = storageUnitEntity.get(StorageUnitEntity_.directoryPath);
    Path<String> businessObjectDataStatusColumn = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.statusCode);
    Path<String> storageUnitStatusColumn = storageUnitEntity.get(StorageUnitEntity_.statusCode);
    Path<Boolean> storageUnitAvailableColumn = storageUnitStatusEntity.get(StorageUnitStatusEntity_.available);

    // Add the clauses for the query.
    criteria.multiselect(storageUnitIdColumn, namespaceCodeColumn, businessObjectDefinitionNameColumn,
            businessObjectFormatUsageColumn, fileTypeColumn, businessObjectFormatVersionColumn,
            primaryPartitionValueColumn, subPartitionValue1Column, subPartitionValue2Column,
            subPartitionValue3Column, subPartitionValue4Column, businessObjectDataVersionColumn,
            storageNameColumn, storageUnitDirectoryPathColumn, businessObjectDataStatusColumn,
            storageUnitStatusColumn, storageUnitAvailableColumn).where(mainQueryRestriction).orderBy(orderBy);

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

    // Build a list of storage unit availability DTOs to return.
    List<StorageUnitAvailabilityDto> storageUnitAvailabilityDtos = new ArrayList<>();
    for (Tuple tuple : tuples) {
        storageUnitAvailabilityDtos.add(new StorageUnitAvailabilityDto(tuple.get(storageUnitIdColumn),
                new BusinessObjectDataKey(tuple.get(namespaceCodeColumn),
                        tuple.get(businessObjectDefinitionNameColumn),
                        tuple.get(businessObjectFormatUsageColumn), tuple.get(fileTypeColumn),
                        tuple.get(businessObjectFormatVersionColumn), tuple.get(primaryPartitionValueColumn),
                        getSubPartitionValuesFromRawSubPartitionValues(Arrays.asList(
                                tuple.get(subPartitionValue1Column), tuple.get(subPartitionValue2Column),
                                tuple.get(subPartitionValue3Column), tuple.get(subPartitionValue4Column))),
                        tuple.get(businessObjectDataVersionColumn)),
                tuple.get(storageNameColumn), tuple.get(storageUnitDirectoryPathColumn),
                tuple.get(businessObjectDataStatusColumn), tuple.get(storageUnitStatusColumn),
                tuple.get(storageUnitAvailableColumn)));
    }

    return storageUnitAvailabilityDtos;
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

@Override
public List<RuleBaseValues> search(String docTypeName, String ruleId, String ruleTemplateId,
        String ruleDescription, String groupId, String principalId, Boolean delegateRule, Boolean activeInd,
        Map extensionValues, String workflowIdDirective) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<RuleBaseValues> cq = cb.createQuery(RuleBaseValues.class);
    Root<RuleBaseValues> root = cq.from(RuleBaseValues.class);
    List<javax.persistence.criteria.Predicate> predicates = getSearchCriteria(root, cq, docTypeName,
            ruleTemplateId, ruleDescription, delegateRule, activeInd, extensionValues);

    if (ruleId != null) {
        predicates.add(cb.equal(root.get("id"), ruleId));
    }//from w ww  .  j  av a2 s. c  o m
    if (groupId != null) {
        predicates.add(cb.in(root.get("id")).value(getRuleResponsibilitySubQuery(groupId, cq)));
    }
    Collection<String> kimGroupIds = new HashSet<String>();
    Boolean searchUser = Boolean.FALSE;
    Boolean searchUserInWorkgroups = Boolean.FALSE;

    if ("group".equals(workflowIdDirective)) {
        searchUserInWorkgroups = Boolean.TRUE;
    } else if (StringUtils.isBlank(workflowIdDirective)) {
        searchUser = Boolean.TRUE;
        searchUserInWorkgroups = Boolean.TRUE;
    } else {
        searchUser = Boolean.TRUE;
    }

    if (!org.apache.commons.lang.StringUtils.isEmpty(principalId) && searchUserInWorkgroups) {
        Principal principal = null;

        principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId);

        if (principal == null) {
            throw new RiceRuntimeException("Failed to locate user for the given principal id: " + principalId);
        }
        kimGroupIds = KimApiServiceLocator.getGroupService().getGroupIdsByPrincipalId(principalId);
    }
    Subquery<RuleResponsibilityBo> subquery = addResponsibilityCriteria(cq, kimGroupIds, principalId,
            searchUser, searchUserInWorkgroups);

    if (subquery != null) {
        predicates.add(cb.in(root.get("id")).value(subquery));
    }
    cq.distinct(true);
    javax.persistence.criteria.Predicate[] preds = predicates
            .toArray(new javax.persistence.criteria.Predicate[predicates.size()]);
    cq.where(preds);
    TypedQuery<RuleBaseValues> q = getEntityManager().createQuery(cq);

    return q.getResultList();
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

@Override
public List<RuleBaseValues> search(String docTypeName, String ruleTemplateId, String ruleDescription,
        Collection<String> workgroupIds, String workflowId, Boolean delegateRule, Boolean activeInd,
        Map extensionValues, Collection actionRequestCodes) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<RuleBaseValues> cq = cb.createQuery(RuleBaseValues.class);
    Root<RuleBaseValues> root = cq.from(RuleBaseValues.class);
    List<javax.persistence.criteria.Predicate> predicates = getSearchCriteria(root, cq, docTypeName,
            ruleTemplateId, ruleDescription, delegateRule, activeInd, extensionValues);
    Subquery<RuleResponsibilityBo> subquery = addResponsibilityCriteria(cq, workgroupIds, workflowId,
            actionRequestCodes, (workflowId != null), ((workgroupIds != null) && !workgroupIds.isEmpty()));
    if (subquery != null) {
        predicates.add(cb.in(root.get("id")).value(subquery));
    }// w  w w.  j av  a  2s  . com
    javax.persistence.criteria.Predicate[] preds = predicates
            .toArray(new javax.persistence.criteria.Predicate[predicates.size()]);
    cq.where(preds);
    TypedQuery<RuleBaseValues> q = getEntityManager().createQuery(cq);

    return q.getResultList();
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private List<javax.persistence.criteria.Predicate> getSearchCriteria(Root<RuleBaseValues> root,
        CriteriaQuery<RuleBaseValues> query, String docTypeName, String ruleTemplateId, String ruleDescription,
        Boolean delegateRule, Boolean activeInd, Map extensionValues) {
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    predicates.add(cb.equal(root.get("currentInd"), Boolean.TRUE));
    predicates.add(cb.equal(root.get("templateRuleInd"), Boolean.FALSE));
    if (activeInd != null) {
        predicates.add(cb.equal(root.get("active"), activeInd));
    }/*from   w  w w  . j ava2s.c o  m*/
    if (docTypeName != null) {
        predicates.add(cb.like(cb.upper(root.<String>get("docTypeName")), docTypeName.toUpperCase()));
    }
    if (ruleDescription != null && !ruleDescription.trim().equals("")) {
        predicates.add(cb.like(cb.upper(root.<String>get("description")), ruleDescription.toUpperCase()));
    }
    if (ruleTemplateId != null) {
        predicates.add(cb.equal(root.get("ruleTemplateId"), ruleTemplateId));
    }
    if (delegateRule != null) {
        predicates.add(cb.equal(root.get("delegateRule"), delegateRule));
    }
    if (extensionValues != null && !extensionValues.isEmpty()) {
        for (Iterator iter2 = extensionValues.entrySet().iterator(); iter2.hasNext();) {
            Map.Entry entry = (Map.Entry) iter2.next();
            if (!StringUtils.isEmpty((String) entry.getValue())) {
                Subquery ruleExtSubQuery = query.subquery(RuleExtensionBo.class);
                Root<RuleExtensionBo> ruleExtRoot = ruleExtSubQuery.from(RuleExtensionBo.class);
                javax.persistence.criteria.Predicate predAnd = cb.and(
                        cb.equal(ruleExtRoot.get("extensionValues").get("key"), entry.getKey()),
                        cb.like(ruleExtRoot.get("extensionValues").<String>get("value"),
                                ("%" + (String) entry.getValue() + "%").toUpperCase()));
                ruleExtSubQuery.where(predAnd);
                ruleExtSubQuery.select(ruleExtRoot.get("ruleBaseValuesId"));

                predicates.add(cb.in(root.get("id")).value(ruleExtSubQuery));
            }
        }
    }
    return predicates;
}

From source file:org.seedstack.i18n.rest.internal.KeyJpaFinder.java

/**
 * Extracts predicates from criteria./* w w w . j a va 2 s .c  o  m*/
 *
 * @param criteria criteria
 * @param cb       criteria builder
 * @param k        root key
 * @return list of predicate
 */
private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb,
        Root<Key> k) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (criteria != null) {
        // extract criteria from the map
        Boolean isApprox = (Boolean) criteria.get(IS_APPROX);
        Boolean isMissing = (Boolean) criteria.get(IS_MISSING);
        Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED);
        String searchName = (String) criteria.get(SEARCH_NAME);

        // is the key LIKE searchName
        if (StringUtils.isNotBlank(searchName)) {
            predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%"));
        }
        // is the key outdated
        if (isOutdated != null) {
            predicates.add(cb.equal(k.<Boolean>get(OUTDATED), isOutdated));
        }

        // if a default translation is available
        String defaultLocale = localeService.getDefaultLocale();
        if (defaultLocale != null && isApprox != null) {
            // join translation table
            Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT);
            // WHERE locale = default locale
            predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), defaultLocale));

            // is the translation approximate
            predicates.add(cb.equal(tln.get(APPROXIMATE), isApprox));
        }

        // is the translation missing
        if (isMissing != null) {
            // SubQuery to find all the key which get a translation for the default locale
            //noinspection unchecked
            Subquery<String> subquery = q.subquery(String.class);
            Root<Key> fromKey = subquery.from(Key.class);
            subquery.select(fromKey.<String>get(ENTITY_ID));
            Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);
            subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), defaultLocale),
                    cb.notEqual(join.get(VALUE), "")));
            // Find all keys not in the above subquery, ie. all the keys missing
            predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery)));
        }
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}

From source file:org.seedstack.i18n.rest.internal.TranslationJpaFinder.java

/**
 * Extracts predicates from criteria./*from  w w  w  .ja  v  a 2s  .  co m*/
 *
 * @param criteria criteria
 * @param cb       criteria builder
 * @param k        root key
 * @return list of predicate
 */
private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb,
        Root<Key> k) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (criteria != null) {
        // extract criteria from the map
        Boolean isApprox = (Boolean) criteria.get(IS_APPROX);
        Boolean isMissing = (Boolean) criteria.get(IS_MISSING);
        Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED);
        String searchName = (String) criteria.get(SEARCH_NAME);
        String locale = (String) criteria.get(LOCALE);

        // is the key LIKE searchName
        if (StringUtils.isNotBlank(searchName)) {
            predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%"));
        }

        // if a default translation is available
        if (isApprox != null || isOutdated != null) {
            // join translation table
            Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT);
            // WHERE locale = default locale
            predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), locale));

            // is the key outdated
            if (isOutdated != null) {
                predicates.add(cb.equal(tln.<Boolean>get(OUTDATED), isOutdated));
            }

            // is the translation approximate
            if (isApprox != null) {
                predicates.add(cb.equal(tln.<Boolean>get(APPROXIMATE), isApprox));
            }
        }
        // is the translation missing
        if (isMissing != null) {
            // SubQuery to find all the key which get a translation for the default locale
            //noinspection unchecked
            Subquery<String> subquery = q.subquery(String.class);
            Root<Key> fromKey = subquery.from(Key.class);
            subquery.select(fromKey.<String>get(ENTITY_ID));
            Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);
            subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), locale),
                    cb.notEqual(join.get(VALUE), "")));
            // Find all keys not in the above subquery, ie. all the keys missing
            predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery)));
        }
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}