List of usage examples for javax.persistence.criteria CriteriaBuilder and
Predicate and(Expression<Boolean> x, Expression<Boolean> y);
From source file:org.finra.herd.dao.impl.StorageUnitDaoImpl.java
/** * Builds a sub-query to select the maximum business object data version. * * @param builder the criteria builder/*from w w w . j a va 2s . c o m*/ * @param criteria the criteria query * @param businessObjectDefinitionEntity the business object definition entity that appears in the from clause of the main query * @param businessObjectFormatEntity the business object format entity that appears in the from clause of the main query * @param fileTypeEntity the file type entity that appears in the from clause of the main query * @param businessObjectDataEntity the business object data entity that appears in the from clause of the main query * @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 * @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 selectOnlyAvailableStorageUnits specifies if only available storage units will be selected or any storage units regardless of their status * * @return the sub-query to select the maximum business object data version */ private Subquery<Integer> getMaximumBusinessObjectFormatVersionSubQuery(CriteriaBuilder builder, CriteriaQuery<?> criteria, From<?, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity, From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, From<?, FileTypeEntity> fileTypeEntity, From<?, BusinessObjectDataEntity> businessObjectDataEntity, Integer businessObjectDataVersion, String businessObjectDataStatus, List<String> storageNames, String storagePlatformType, String excludedStoragePlatformType, boolean selectOnlyAvailableStorageUnits) { // Business object format version is not specified, so just use the latest available for this set of partition values. Subquery<Integer> subQuery = criteria.subquery(Integer.class); // The criteria root is the business object data. Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subQuery.from(BusinessObjectDataEntity.class); // Join to the other tables we can filter on. Join<BusinessObjectDataEntity, StorageUnitEntity> subStorageUnitEntity = subBusinessObjectDataEntity .join(BusinessObjectDataEntity_.storageUnits); Join<StorageUnitEntity, StorageEntity> subStorageEntity = subStorageUnitEntity .join(StorageUnitEntity_.storage); Join<StorageEntity, StoragePlatformEntity> subStoragePlatformEntity = subStorageEntity .join(StorageEntity_.storagePlatform); Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> subBusinessObjectFormatEntity = subBusinessObjectDataEntity .join(BusinessObjectDataEntity_.businessObjectFormat); Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> subBusinessObjectDefinitionEntity = subBusinessObjectFormatEntity .join(BusinessObjectFormatEntity_.businessObjectDefinition); Join<BusinessObjectFormatEntity, FileTypeEntity> subBusinessObjectFormatFileTypeEntity = subBusinessObjectFormatEntity .join(BusinessObjectFormatEntity_.fileType); Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> subBusinessObjectDataStatusEntity = subBusinessObjectDataEntity .join(BusinessObjectDataEntity_.status); Join<StorageUnitEntity, StorageUnitStatusEntity> subStorageUnitStatusEntity = subStorageUnitEntity .join(StorageUnitEntity_.status); // Create the standard restrictions (i.e. the standard where clauses). Predicate subQueryRestriction = builder.equal(subBusinessObjectDefinitionEntity, businessObjectDefinitionEntity); subQueryRestriction = builder.and(subQueryRestriction, builder.equal(subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage), businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage))); subQueryRestriction = builder.and(subQueryRestriction, builder.equal(subBusinessObjectFormatFileTypeEntity, fileTypeEntity)); // Create and add standard restrictions on primary and sub-partition values. subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnPartitionValues(builder, subBusinessObjectDataEntity, businessObjectDataEntity)); // Add restrictions on business object data version and business object data status. Predicate subQueryRestrictionOnBusinessObjectDataVersionAndStatus = getQueryRestrictionOnBusinessObjectDataVersionAndStatus( builder, subBusinessObjectDataEntity, subBusinessObjectDataStatusEntity, businessObjectDataVersion, businessObjectDataStatus); if (subQueryRestrictionOnBusinessObjectDataVersionAndStatus != null) { subQueryRestriction = builder.and(subQueryRestriction, subQueryRestrictionOnBusinessObjectDataVersionAndStatus); } // Create and add a standard restriction on storage. subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnStorage(builder, subStorageEntity, subStoragePlatformEntity, storageNames, storagePlatformType, excludedStoragePlatformType)); // If specified, add a restriction on storage unit status availability flag. if (selectOnlyAvailableStorageUnits) { subQueryRestriction = builder.and(subQueryRestriction, builder.isTrue(subStorageUnitStatusEntity.get(StorageUnitStatusEntity_.available))); } // Add all of the clauses to the subquery. subQuery.select(builder .max(subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion))) .where(subQueryRestriction); return subQuery; }
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// ww w .jav a 2s.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.finra.herd.dao.impl.StorageUnitNotificationRegistrationDaoImpl.java
@Override public StorageUnitNotificationRegistrationEntity getStorageUnitNotificationRegistrationByAltKey( NotificationRegistrationKey key) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StorageUnitNotificationRegistrationEntity> criteria = builder .createQuery(StorageUnitNotificationRegistrationEntity.class); // The criteria root is the storage unit notification registration entity. Root<StorageUnitNotificationRegistrationEntity> businessObjectDataNotificationEntity = criteria .from(StorageUnitNotificationRegistrationEntity.class); // Join to the other tables we can filter on. Join<StorageUnitNotificationRegistrationEntity, NamespaceEntity> namespaceEntity = businessObjectDataNotificationEntity .join(StorageUnitNotificationRegistrationEntity_.namespace); // Create the standard restrictions (i.e. the standard where clauses). Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), key.getNamespace().toUpperCase()); queryRestriction = builder.and(queryRestriction, builder.equal( builder.upper(/* w w w .j av a2s. c o m*/ businessObjectDataNotificationEntity.get(StorageUnitNotificationRegistrationEntity_.name)), key.getNotificationName().toUpperCase())); criteria.select(businessObjectDataNotificationEntity).where(queryRestriction); return executeSingleResultQuery(criteria, String.format( "Found more than one storage unit notification registration with with parameters {namespace=\"%s\", notificationName=\"%s\"}.", key.getNamespace(), key.getNotificationName())); }
From source file:org.ibankapp.base.persistence.validation.validator.UniqueValidator.java
@SuppressWarnings("unchecked") public static <T> void validate(T bean, EntityManager em) { EntityInformation ei = new EntityInformation(bean.getClass(), em.getMetamodel()); Iterable<String> idAttributeNames = ei.getIdAttributeNames(); List<Unique> uniqueList = new ArrayList<>(); if (bean.getClass().isAnnotationPresent(Uniques.class)) { Uniques uniques = bean.getClass().getAnnotation(Uniques.class); Collections.addAll(uniqueList, uniques.constraints()); }/*ww w. jav a2s. c o m*/ if (bean.getClass().isAnnotationPresent(Unique.class)) { uniqueList.add(bean.getClass().getAnnotation(Unique.class)); } for (Unique unique : uniqueList) { String[] properties = unique.properties(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<?> c = cb.createQuery(bean.getClass()); Root<?> root = c.from(bean.getClass()); Predicate condition = cb.conjunction(); try { for (String idAttributeName : idAttributeNames) { condition = cb.and(condition, cb.notEqual(root.get(idAttributeName), PropertyUtils.getProperty(bean, idAttributeName))); } for (String property : properties) { condition = cb.and(condition, cb.equal(root.get(property), PropertyUtils.getProperty(bean, property))); } } catch (Exception e) { throw new BaseException("E-BASE-000001", e.getMessage()).initCause(e); } c.where(condition); int count = em.createQuery(c).getResultList().size(); if (count != 0) { throw new BaseException("E-BASE-000008", unique.message()); } } }
From source file:org.jasig.portal.events.aggr.JpaBaseAggregationDao.java
@Override public final void afterPropertiesSet() throws Exception { this.timeDimensionParameter = this.createParameterExpression(TimeDimension.class, "timeDimension"); this.dateDimensionParameter = this.createParameterExpression(DateDimension.class, "dateDimension"); this.intervalParameter = this.createParameterExpression(AggregationInterval.class, "interval"); this.aggregatedGroupParameter = this.createParameterExpression(AggregatedGroupMapping.class, "aggregatedGroup"); this.aggregatedGroupsParameter = this.createParameterExpression(Set.class, "aggregatedGroups"); this.startDate = this.createParameterExpression(LocalDate.class, "startDate"); this.endMinusOneDate = this.createParameterExpression(LocalDate.class, "endMinusOneDate"); this.endDate = this.createParameterExpression(LocalDate.class, "endDate"); this.startTime = this.createParameterExpression(LocalTime.class, "startTime"); this.endTime = this.createParameterExpression(LocalTime.class, "endTime"); this.createParameterExpressions(); this.findAggregationByDateTimeIntervalQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override//from w ww . ja v a 2s. c om public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); addFetches(ba); criteriaQuery.select(ba); criteriaQuery.where( cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter), cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter), cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); return criteriaQuery; } }); this.findAggregationByDateTimeIntervalGroupQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); final List<Predicate> keyPredicates = new ArrayList<Predicate>(); keyPredicates .add(cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter)); keyPredicates .add(cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter)); keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); keyPredicates.add( cb.equal(ba.get(BaseAggregationImpl_.aggregatedGroup), aggregatedGroupParameter)); addAggregationSpecificKeyPredicate(cb, ba, keyPredicates); criteriaQuery.select(ba); criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()])); return criteriaQuery; } }); this.findAggregationsByDateRangeQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension, JoinType.LEFT); final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension, JoinType.LEFT); final List<Predicate> keyPredicates = new ArrayList<Predicate>(); keyPredicates.add(cb.and( //Restrict results by outer date range cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate), cb.lessThan(dd.get(DateDimensionImpl_.date), endDate))); keyPredicates.add(cb.or( //Restrict start of range by time as well cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate), cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime))); keyPredicates.add(cb.or( //Restrict end of range by time as well cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate), cb.lessThan(td.get(TimeDimensionImpl_.time), endTime))); keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); keyPredicates .add(ba.get(BaseAggregationImpl_.aggregatedGroup).in(aggregatedGroupsParameter)); addAggregationSpecificKeyPredicate(cb, ba, keyPredicates); criteriaQuery.select(ba); criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()])); criteriaQuery.orderBy(cb.desc(dd.get(DateDimensionImpl_.date)), cb.desc(td.get(TimeDimensionImpl_.time))); return criteriaQuery; } }); /* * Similar to the previous query but only returns aggregates that also match the unclosed predicate generated * by the subclass. This is used for finding aggregates that missed having intervalComplete called due to * interval boundary placement. */ this.findUnclosedAggregationsByDateRangeQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension, JoinType.LEFT); final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension, JoinType.LEFT); addFetches(ba); final List<Predicate> keyPredicates = new ArrayList<Predicate>(); keyPredicates.add(cb.and( //Restrict results by outer date range cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate), cb.lessThan(dd.get(DateDimensionImpl_.date), endDate))); keyPredicates.add(cb.or( //Restrict start of range by time as well cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate), cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime))); keyPredicates.add(cb.or( //Restrict end of range by time as well cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate), cb.lessThan(td.get(TimeDimensionImpl_.time), endTime))); keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); //No aggregation specific key bits here, we only have start/end/interval parameters to work with addUnclosedPredicate(cb, ba, keyPredicates); criteriaQuery.select(ba); criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()])); return criteriaQuery; } }); this.createCriteriaQueries(); }
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 ww w . j a v a 2 s. c om*/ 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.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}//from ww w. jav a2 s . c o m */ @Override public List<Image> findImages(Integer volNum, String volLetExt) throws PersistenceException { // Create criteria objects CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class); Root<Image> root = criteriaQuery.from(Image.class); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt")) : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText))); // Set values in predicate's elements TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery); typedQuery.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { typedQuery.setParameter("volLetExt", volLetExt); } return typedQuery.getResultList(); }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}//w ww.j a va2 s .c om */ @SuppressWarnings("rawtypes") @Override public Page findImages(Integer volNum, String volLetExt, PaginationFilter paginationFilter) throws PersistenceException { // Create criteria objects CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); Page page = new Page(paginationFilter); if (paginationFilter.getTotal() == null) { CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Image> rootCount = criteriaQueryCount.from(Image.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQueryCount .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt")) : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); typedQueryCount.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { typedQueryCount.setParameter("volLetExt", volLetExt); } page.setTotal(new Long((Long) typedQueryCount.getSingleResult())); } CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class); Root<Image> root = criteriaQuery.from(Image.class); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); //We need to duplicate predicates beacause they are link to Root element criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt")) : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText))); // Set values in predicate's elements TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery); typedQuery.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { typedQuery.setParameter("volLetExt", volLetExt); } //Pagination will work with index [1 ... total] and not [0 ... total1-] typedQuery.setFirstResult(paginationFilter.getFirstRecord() - 1); typedQuery.setMaxResults(paginationFilter.getLength()); page.setList(typedQuery.getResultList()); return page; }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}// w w w . ja v a2 s . c o m */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public FoliosInformations findVolumeFoliosInformations(Integer volNum, String volLetExt) throws PersistenceException { FoliosInformations foliosInformations = new FoliosInformations(); CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Image> rootCount = criteriaQueryCount.from(Image.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQueryCount .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt")) : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); typedQueryCount.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) typedQueryCount.setParameter("volLetExt", volLetExt); foliosInformations.setTotal((Long) typedQueryCount.getSingleResult()); StringBuilder stringBuilder = new StringBuilder( "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt "); if (!StringUtils.isEmpty(volLetExt)) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" is null"); stringBuilder.append(" GROUP BY imageType, imageRectoVerso"); Query query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { query.setParameter("volLetExt", volLetExt); } List<Object[]> result = (List<Object[]>) query.getResultList(); // We init every partial-total foliosInformations.setTotalRubricario(new Long(0)); foliosInformations.setTotalCarta(new Long(0)); foliosInformations.setTotalAppendix(new Long(0)); foliosInformations.setTotalOther(new Long(0)); foliosInformations.setTotalGuardia(new Long(0)); foliosInformations.setTotalMissingFolios(0); // We set new partial-total values for (int i = 0; i < result.size(); i++) { // This is an array defined as [ImageType, Count by ImageType] Object[] singleGroup = result.get(i); if (((ImageType) singleGroup[0]).equals(ImageType.R)) { if (foliosInformations.getTotalRubricario() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalRubricario(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) { if (foliosInformations.getTotalCarta() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalCarta(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) { if (foliosInformations.getTotalAppendix() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalAppendix(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) { if (foliosInformations.getTotalOther() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalOther(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) { if (foliosInformations.getTotalGuardia() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalGuardia(new Long(singleGroup[2].toString())); } } } // Calculating missing folios start stringBuilder = new StringBuilder( "SELECT DISTINCT(imageProgTypeNum) FROM Image WHERE volNum = :volNum AND volLetExt "); if (!StringUtils.isEmpty(volLetExt)) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" IS NULL"); stringBuilder.append(" AND imageType = 'C'"); // we search only for folios stringBuilder.append(" ORDER BY imageProgTypeNum ASC"); query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { query.setParameter("volLetExt", volLetExt); } List<Integer> foliosOnVolume = (List<Integer>) query.getResultList(); for (long i = 1; i <= foliosInformations.getTotalCarta(); i++) { for (int j = 0; j < foliosOnVolume.size(); j++) { if (foliosOnVolume.get(j) == i) { break; } else if (foliosOnVolume.get(j) > i) { foliosInformations.setTotalMissingFolios(foliosInformations.getTotalMissingFolios() + 1); //LP : Missing numbering is first counter!!!! foliosInformations.getMissingNumberingFolios().add(((Long) i).intValue()); break; } } } // Calculating missing folios end //Extracting misnumbered Folios... stringBuilder = new StringBuilder( "SELECT concat(imageProgTypeNum, missedNumbering) FROM Image WHERE volNum=:volNum and volLetExt "); if (!StringUtils.isEmpty(volLetExt)) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" is null"); stringBuilder.append(" and missedNumbering is not null ORDER BY imageProgTypeNum ASC"); query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { query.setParameter("volLetExt", volLetExt); } foliosInformations.setMisnumberedFolios((List<String>) query.getResultList()); return foliosInformations; }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * This method updates every totals in input. * /*from w w w . j av a 2s.co m*/ * @param explorer input object to be update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private <T extends VolumeExplorer> void updateExplorerTotals(T explorer) { CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Image> rootCount = criteriaQueryCount.from(Image.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQueryCount .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum), StringUtils.isEmpty(explorer.getVolLetExt()) ? criteriaBuilder.isNull(rootCount.get("volLetExt")) : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); typedQueryCount.setParameter("volNum", explorer.getVolNum()); if (!StringUtils.isEmpty(explorer.getVolLetExt())) typedQueryCount.setParameter("volLetExt", explorer.getVolLetExt()); explorer.setTotal((Long) typedQueryCount.getSingleResult()); StringBuilder stringBuilder = new StringBuilder( "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt "); if (!StringUtils.isEmpty(explorer.getVolLetExt())) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" is null"); stringBuilder.append(" group by imageType, imageRectoVerso"); Query query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", explorer.getVolNum()); if (!StringUtils.isEmpty(explorer.getVolLetExt())) { query.setParameter("volLetExt", explorer.getVolLetExt()); } List<Object[]> result = (List<Object[]>) query.getResultList(); // We init every partial-total explorer.setTotalRubricario(new Long(0)); explorer.setTotalCarta(new Long(0)); explorer.setTotalAppendix(new Long(0)); explorer.setTotalOther(new Long(0)); explorer.setTotalGuardia(new Long(0)); // We set new partial-total values for (int i = 0; i < result.size(); i++) { // This is an array defined as [ImageType, Count by ImageType] Object[] singleGroup = result.get(i); if (((ImageType) singleGroup[0]).equals(ImageType.R)) { if (explorer.getTotalRubricario() < new Long(singleGroup[2].toString())) { explorer.setTotalRubricario(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) { if (explorer.getTotalCarta() < new Long(singleGroup[2].toString())) { explorer.setTotalCarta(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) { if (explorer.getTotalAppendix() < new Long(singleGroup[2].toString())) { explorer.setTotalAppendix(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) { if (explorer.getTotalOther() < new Long(singleGroup[2].toString())) { explorer.setTotalOther(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) { if (explorer.getTotalGuardia() < new Long(singleGroup[2].toString())) { explorer.setTotalGuardia(new Long(singleGroup[2].toString())); } } } }