Java Code Examples for javax.persistence.criteria.Subquery#from()

The following examples show how to use javax.persistence.criteria.Subquery#from() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PostServiceImpl.java    From halo with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Build specification by post query.
 *
 * @param postQuery post query must not be null
 * @return a post specification
 */
@NonNull
private Specification<Post> buildSpecByQuery(@NonNull PostQuery postQuery) {
    Assert.notNull(postQuery, "Post query must not be null");

    return (Specification<Post>) (root, query, criteriaBuilder) -> {
        List<Predicate> predicates = new LinkedList<>();

        if (postQuery.getStatus() != null) {
            predicates.add(criteriaBuilder.equal(root.get("status"), postQuery.getStatus()));
        }

        if (postQuery.getCategoryId() != null) {
            Subquery<Post> postSubquery = query.subquery(Post.class);
            Root<PostCategory> postCategoryRoot = postSubquery.from(PostCategory.class);
            postSubquery.select(postCategoryRoot.get("postId"));
            postSubquery.where(
                criteriaBuilder.equal(root.get("id"), postCategoryRoot.get("postId")),
                criteriaBuilder.equal(postCategoryRoot.get("categoryId"),
                    postQuery.getCategoryId()));
            predicates.add(criteriaBuilder.exists(postSubquery));
        }

        if (postQuery.getKeyword() != null) {
            // Format like condition
            String likeCondition = String
                .format("%%%s%%", StringUtils.strip(postQuery.getKeyword()));

            // Build like predicate
            Predicate titleLike = criteriaBuilder.like(root.get("title"), likeCondition);
            Predicate originalContentLike = criteriaBuilder
                .like(root.get("originalContent"), likeCondition);

            predicates.add(criteriaBuilder.or(titleLike, originalContentLike));
        }

        return query.where(predicates.toArray(new Predicate[0])).getRestriction();
    };
}
 
Example 2
Source File: PageSpecifications.java    From wallride with Apache License 2.0 6 votes vote down vote up
public static Specification<Page> draft(Page page) {
	return (root, query, cb) -> {
		List<Predicate> predicates = new ArrayList<>();
		predicates.add(cb.equal(root.get(Page_.drafted), page));

		Subquery<Long> subquery = query.subquery(Long.class);
		Root<Page> p = subquery.from(Page.class);
		subquery.select(cb.max(p.get(Page_.id))).where(cb.equal(p.get(Page_.drafted), page));

		predicates.add(cb.equal(root.get(Page_.id), subquery));
		return cb.and(predicates.toArray(new Predicate[0]));
	};
}
 
Example 3
Source File: EmployeeSearchServiceImpl.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public List<DeptEmployee> searchByDepartmentQuery(String searchKey) {
    CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
    Root<DeptEmployee> emp = criteriaQuery.from(DeptEmployee.class);

    Subquery<Department> subquery = criteriaQuery.subquery(Department.class);
    Root<Department> dept = subquery.from(Department.class);
    subquery.select(dept)
        .distinct(true)
        .where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey)
            .append("%")
            .toString()));

    criteriaQuery.select(emp)
        .where(criteriaBuilder.in(emp.get("department"))
            .value(subquery));

    TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
    return query.getResultList();
}
 
Example 4
Source File: BuildRecordPredicates.java    From pnc with Apache License 2.0 6 votes vote down vote up
/**
 * (related to NCL-5192, NCL-5351)
 *
 * When (re)building a temporary build: - if there are existing *successful* temporary builds having the same idRev,
 * ignore persistent builds - if there are no existing temporary builds having the same idRev, include also
 * persistent builds having the same idRev
 *
 * When (re)building a persistent build: - include only existing persistent builds having the same idRev
 *
 * @param idRev the revision of the build to (re)build
 * @param temporary if requested (re)build is temporary
 * @return Predicate that filters out builds according to description
 */
public static Predicate<BuildRecord> includeTemporary(IdRev idRev, boolean temporary) {
    return (root, query, cb) -> {
        if (temporary) {
            // Create subquery that counts number of temporary builds for the same BuildConfigurationAudited.idRev
            Subquery<Long> temporaryCount = query.subquery(Long.class);
            Root<BuildRecord> subRoot = temporaryCount.from(BuildRecord.class);
            temporaryCount.select(cb.count(subRoot.get(BuildRecord_.id)));
            temporaryCount.where(
                    cb.and(
                            cb.isTrue(subRoot.get(BuildRecord_.temporaryBuild)),
                            cb.equal(subRoot.get(BuildRecord_.status), BuildStatus.SUCCESS),
                            cb.equal(subRoot.get(BuildRecord_.buildConfigurationId), idRev.getId()),
                            cb.equal(subRoot.get(BuildRecord_.buildConfigurationRev), idRev.getRev())));

            // only false if build is persistent and there are temporaryBuilds present
            return cb
                    .or(cb.isTrue(root.get(BuildRecord_.temporaryBuild)), cb.lessThanOrEqualTo(temporaryCount, 0L));
        }
        return cb.isFalse(root.get(BuildRecord_.temporaryBuild));
    };
}
 
Example 5
Source File: SecurityFunctionDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public List<String> getUnrestrictedSecurityFunctions()
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

    // The criteria root is the security function.
    Root<SecurityFunctionEntity> securityFunctionEntityRoot = criteria.from(SecurityFunctionEntity.class);

    // Build a subquery to eliminate security functions that are mapped to security roles.
    Subquery<SecurityFunctionEntity> subquery = criteria.subquery(SecurityFunctionEntity.class);
    Root<SecurityRoleFunctionEntity> subSecurityRoleFunctionEntityRoot = subquery.from(SecurityRoleFunctionEntity.class);
    subquery.select(subSecurityRoleFunctionEntityRoot.get(SecurityRoleFunctionEntity_.securityFunction))
        .where(builder.equal(subSecurityRoleFunctionEntityRoot.get(SecurityRoleFunctionEntity_.securityFunction), securityFunctionEntityRoot));

    // Get the security function code column.
    Path<String> functionCodeColumn = securityFunctionEntityRoot.get(SecurityFunctionEntity_.code);

    // Add the clauses for the query.
    criteria.select(functionCodeColumn).where(builder.not(builder.exists(subquery))).orderBy(builder.asc(functionCodeColumn));

    // Run the query to get a list of unrestricted security functions.
    return entityManager.createQuery(criteria).getResultList();
}
 
Example 6
Source File: RSQLUtility.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate toNotExistsSubQueryPredicate(final String[] fieldNames, final A enumField,
        final Function<Expression<String>, Predicate> subQueryPredicateProvider) {
    final Class<?> javaType = root.getJavaType();
    final Subquery<?> subquery = query.subquery(javaType);
    final Root subqueryRoot = subquery.from(javaType);
    final Predicate equalPredicate = cb.equal(root.get(enumField.identifierFieldName()),
            subqueryRoot.get(enumField.identifierFieldName()));
    final Path innerFieldPath = getInnerFieldPath(subqueryRoot, fieldNames, enumField.isMap());
    final Expression<String> expressionToCompare = getExpressionToCompare(innerFieldPath, enumField);
    final Predicate subQueryPredicate = subQueryPredicateProvider.apply(expressionToCompare);
    subquery.select(subqueryRoot).where(cb.and(equalPredicate, subQueryPredicate));
    return cb.not(cb.exists(subquery));
}
 
Example 7
Source File: RuleDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private Subquery<RuleResponsibilityBo> getRuleResponsibilitySubQuery(String ruleRespName,
                    CriteriaQuery<RuleBaseValues> query){
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = subquery.from(RuleResponsibilityBo.class);
    subquery.where(cb.equal(fromResp.get("ruleResponsibilityName"),ruleRespName));
    subquery.select(fromResp.get("ruleBaseValuesId"));

    return subquery;
}
 
Example 8
Source File: CommandPredicates.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get the specification for the query which will find the commands which match the given criterion.
 *
 * @param root      The {@link Root} (from) for the query
 * @param cq        The {@link CriteriaQuery} instance
 * @param cb        The {@link CriteriaBuilder} instance
 * @param criterion The {@link Criterion} to match commands against
 * @return A {@link Predicate} for this query
 */
public static Predicate findCommandsMatchingCriterion(
    final Root<CommandEntity> root,
    final CriteriaQuery<?> cq,
    final CriteriaBuilder cb,
    final Criterion criterion
) {
    final Subquery<Long> criterionSubquery = cq.subquery(Long.class);
    final Root<CommandEntity> criterionSubqueryRoot = criterionSubquery.from(CommandEntity.class);
    criterionSubquery.select(criterionSubqueryRoot.get(CommandEntity_.id));
    criterionSubquery.where(
        cb.and(
            PredicateUtils.createCriterionPredicate(
                criterionSubqueryRoot,
                criterionSubquery,
                cb,
                CommandEntity_.uniqueId,
                CommandEntity_.name,
                CommandEntity_.version,
                CommandEntity_.status,
                () -> criterionSubqueryRoot.join(CommandEntity_.tags, JoinType.INNER),
                CommandEntity_.id,
                criterion
            ),
            cb.isNotEmpty(criterionSubqueryRoot.get(CommandEntity_.clusterCriteria))
        )
    );

    return root.get(CommandEntity_.id).in(criterionSubquery);
}
 
Example 9
Source File: PageSpecifications.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static Specification<Page> path(Page page, boolean includeUnpublished) {
		return (root, query, cb) -> {
//			query.distinct(true);
			Root<Page> p1 = query.from(Page.class);
			Root<Page> p2 = root;
			Root<Page> p3 = query.from(Page.class);

			List<Predicate> predicates = new ArrayList<>();
			predicates.add(cb.equal(root.get(Page_.language), page.getLanguage()));
			if (!includeUnpublished) {
				predicates.add(cb.equal(root.get(Page_.status), Page.Status.PUBLISHED));
			}

			Subquery<Long> subquery = query.subquery(Long.class);
			Root<Page> p = subquery.from(Page.class);
			subquery.select(p.get(Page_.id)).where(
					cb.equal(p.get(Page_.language), page.getLanguage()),
					cb.isNull(p.get(Page_.parent)),
					cb.le(p.get(Page_.lft), page.getLft()),
					cb.ge(p.get(Page_.rgt), page.getRgt()));

			predicates.add(cb.equal(p1.get(Page_.id), subquery));
			predicates.add(cb.equal(p3.get(Page_.id), page.getId()));
			predicates.add(cb.between(p2.get(Page_.lft), p1.get(Page_.lft), p1.get(Page_.rgt)));
			predicates.add(cb.between(p3.get(Page_.lft), p2.get(Page_.lft), p2.get(Page_.rgt)));
			query.orderBy(cb.desc(cb.diff(p2.get(Page_.rgt), p2.get(Page_.lft))));
			return cb.and(predicates.toArray(new Predicate[0]));
		};
	}
 
Example 10
Source File: BuildRecordPredicates.java    From pnc with Apache License 2.0 5 votes vote down vote up
public static Predicate<BuildRecord> withoutAttribute(String key) {
    return (root, query, cb) -> {
        Subquery<String> subquery = query.subquery(String.class);
        Root<BuildRecordAttribute> subRoot = subquery.from(BuildRecordAttribute.class);
        subquery.select(subRoot.get(BuildRecordAttribute_.key));
        subquery.where(
                cb.and(
                        cb.equal(subRoot.get(BuildRecordAttribute_.key), key),
                        cb.equal(root.get(BuildRecord_.id), subRoot.get(BuildRecordAttribute_.buildRecord))));
        return query.where(cb.not(cb.exists(subquery))).getRestriction();
    };
}
 
Example 11
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private List<javax.persistence.criteria.Predicate> getSearchCriteria(Root<RuleBaseValues> root,CriteriaQuery<RuleBaseValues> query,
        String docTypeName, String ruleTemplateId,
        String ruleDescription, Boolean activeInd, Map<String,String> extensionValues) {
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    CriteriaBuilder criteribaBuilder = getEntityManager().getCriteriaBuilder();

    predicates.add(criteribaBuilder.equal(root.get("currentInd"),Boolean.TRUE));
    predicates.add(criteribaBuilder.equal(root.get("templateRuleInd"), Boolean.FALSE));
    if (activeInd != null) {
        predicates.add(criteribaBuilder.equal(root.get("active"),activeInd));
    }
    if (docTypeName != null) {
        predicates.add(criteribaBuilder.like(criteribaBuilder.upper(root.<String>get("docTypeName")), docTypeName.toUpperCase()));
    }
    if (ruleDescription != null && !ruleDescription.trim().equals("")) {
        predicates.add(criteribaBuilder.like(criteribaBuilder.upper(root.<String>get("description")),ruleDescription.toUpperCase()));
    }
    if (ruleTemplateId != null) {
        predicates.add(criteribaBuilder.equal(root.get("ruleTemplateId"),ruleTemplateId));
    }

    if (extensionValues != null && !extensionValues.isEmpty()) {
        for (Map.Entry<String,String> entry : extensionValues.entrySet()) {
            if (!StringUtils.isEmpty(entry.getValue())) {
                Subquery ruleExtSubQuery = query.subquery(RuleExtensionBo.class);
                Root<RuleExtensionBo> ruleExtRoot = ruleExtSubQuery.from(RuleExtensionBo.class);
                javax.persistence.criteria.Predicate predAnd = criteribaBuilder.and(
                        criteribaBuilder.equal(ruleExtRoot.get("extensionValues").get("key"),entry.getKey()),
                        criteribaBuilder.like(ruleExtRoot.get("extensionValues").<String>get("value"),
                                ("%" + (String) entry.getValue() + "%").toUpperCase()));
                ruleExtSubQuery.where(predAnd);
                ruleExtSubQuery.select(ruleExtRoot.get("ruleBaseValuesId"));

                predicates.add(criteribaBuilder.in(root.get("id")).value(ruleExtSubQuery));
            }
        }
    }
    return predicates;
}
 
Example 12
Source File: ContestSupervisorHibernateDao.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
static CustomPredicateFilter<ContestModel> hasSupervisor(String userJid) {
    return (cb, cq, root) -> {
        Subquery<ContestSupervisorModel> sq = cq.subquery(ContestSupervisorModel.class);
        Root<ContestSupervisorModel> subRoot = sq.from(ContestSupervisorModel.class);

        sq.where(
                cb.equal(subRoot.get(ContestSupervisorModel_.contestJid), root.get(ContestModel_.jid)),
                cb.equal(subRoot.get(ContestSupervisorModel_.userJid), userJid));
        sq.select(subRoot);

        return cb.exists(sq);
    };
}
 
Example 13
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Method that returns a subquery that selects rule id from rule responsibility table based on certain criteria
 * @param ruleResponsibilityName is the responsibility name
 * @param query is he criteria query
 * @return a subquery that selects the rule id from rule responsibility table where responsibility name equals the rule responsibility name that is passed in as parameter to this method
 */
private Subquery<RuleResponsibilityBo> getResponsibilitySubQuery(String ruleResponsibilityName, CriteriaQuery<RuleBaseValues> query){
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> ruleResponsibilitySubquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = ruleResponsibilitySubquery.from(RuleResponsibilityBo.class);
    ruleResponsibilitySubquery.where(criteriaBuilder.equal(fromResp.get("ruleResponsibilityName"),ruleResponsibilityName));
    ruleResponsibilitySubquery.select(fromResp.get("ruleBaseValuesId"));

    return ruleResponsibilitySubquery;
}
 
Example 14
Source File: TestJpaDao.java    From jdal with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void testCopy() {
	EntityManager em = bookDao.getEntityManager();
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Book> criteria = cb.createQuery(Book.class);
	
	// Fetch join
	Root<Book> root = criteria.from(Book.class);
	Path<String> path = root.join("author").<String>get("name");
	root.fetch("author");
	criteria.select(root);
	
	// SubQuery
	Subquery<String> sq = criteria.subquery(String.class);
	Root<Author> author = sq.from(Author.class);
	sq.select(author.<String>get("name"));
	sq.where(cb.equal(author.<String>get("name"), "Rod"));
	
	criteria.where(cb.in(path).value(sq));
	
	CriteriaQuery<Book> copy = cb.createQuery(Book.class);
	JpaUtils.copyCriteria(criteria, copy);
	
	List<Book> copyBooks = em.createQuery(copy).getResultList();
	List<Book> books = em.createQuery(criteria).getResultList();
	assertEquals(books, copyBooks);
}
 
Example 15
Source File: ContestManagerHibernateDao.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
static CustomPredicateFilter<ContestModel> hasManager(String userJid) {
    return (cb, cq, root) -> {
        Subquery<ContestManagerModel> sq = cq.subquery(ContestManagerModel.class);
        Root<ContestManagerModel> subRoot = sq.from(ContestManagerModel.class);

        sq.where(
                cb.equal(subRoot.get(ContestManagerModel_.contestJid), root.get(ContestModel_.jid)),
                cb.equal(subRoot.get(ContestManagerModel_.userJid), userJid));
        sq.select(subRoot);

        return cb.exists(sq);
    };
}
 
Example 16
Source File: ContestModuleHibernateDao.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
static CustomPredicateFilter<ContestModel> hasModule(ContestModuleType type) {
    return (cb, cq, root) -> {
        Subquery<ContestModuleModel> sq = cq.subquery(ContestModuleModel.class);
        Root<ContestModuleModel> subRoot = sq.from(ContestModuleModel.class);

        sq.where(
                cb.equal(subRoot.get(ContestModuleModel_.contestJid), root.get(ContestModel_.jid)),
                cb.equal(subRoot.get(ContestModuleModel_.name), type.name()),
                cb.isTrue(subRoot.get(ContestModuleModel_.enabled)));
        sq.select(subRoot);

        return cb.exists(sq);
    };
}
 
Example 17
Source File: ResourceDao.java    From osiam with MIT License 4 votes vote down vote up
public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count,
        int startIndex,
        String sortBy, String sortOrder, FilterParser<T> filterParser) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<T> resourceQuery = cb.createQuery(clazz);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class);
    Root<T> internalIdRoot = internalIdQuery.from(clazz);
    internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId));

    if (filterTree != null && filterTree.getChildCount() > 0) {
        Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot);
        internalIdQuery.where(predicate);
    }

    resourceQuery.select(resourceRoot).where(
            cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible
    Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id);

    if (sortBy != null && !sortBy.isEmpty()) {
        sortByField = filterParser.createSortByField(sortBy, resourceRoot);
    }

    // default order is ascending
    Order order = cb.asc(sortByField);

    if (sortOrder.equalsIgnoreCase("descending")) {
        order = cb.desc(sortByField);
    }

    resourceQuery.orderBy(order);

    TypedQuery<T> query = em.createQuery(resourceQuery);
    query.setFirstResult(startIndex);
    query.setMaxResults(count);

    List<T> results = query.getResultList();

    long totalResult = getTotalResults(clazz, internalIdQuery);

    return new SearchResult<>(results, totalResult);
}
 
Example 18
Source File: HibernateIdentifiableObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public List<Function<Root<T>, Predicate>> getDataSharingPredicates( CriteriaBuilder builder, UserInfo user, String access )
{
    List<Function<Root<T>, Predicate>> predicates = new ArrayList<>();

    CriteriaQuery<T> criteria = builder.createQuery( getClazz() );

    preProcessPredicates( builder, predicates );

    if ( !dataSharingEnabled( user ) || user == null )
    {
        return predicates;
    }

    Function<Root<T>, Subquery<Integer>> userGroupPredicate = (( Root<T> root ) -> {
        Subquery<Integer> userGroupSubQuery = criteria.subquery( Integer.class );
        Root<T> ugdc = userGroupSubQuery.from( getClazz() );
        Join<T, UserGroupAccess> uga = ugdc.join( "userGroupAccesses" );
        userGroupSubQuery.select( uga.get( "id" ) );

        return userGroupSubQuery.where(
            builder.and(
                builder.equal( root.get( "id" ), ugdc.get( "id" ) ),
                builder.equal( uga.join( "userGroup" ).join( "members" ).get( "id" ), user.getId() ),
                builder.like( uga.get( "access" ), access ) ) );
    });

    Function<Root<T>, Subquery<Integer>> userPredicate = (root -> {
        Subquery<Integer> userSubQuery = criteria.subquery( Integer.class );
        Root<T> udc = userSubQuery.from( getClazz() );
        Join<T, UserAccess> ua = udc.join( "userAccesses" );
        userSubQuery.select( ua.get( "id" ) );

        return userSubQuery.where(
            builder.and(
                builder.equal( root.get( "id" ), udc.get( "id" ) ),
                builder.equal( ua.get( "user" ).get( "id" ), user.getId() ),
                builder.like( ua.get( "access" ), access ) ) );
    });

    predicates.add( root -> builder.or(
        builder.like( root.get( "publicAccess" ), access ),
        builder.isNull( root.get( "publicAccess" ) ),
        builder.exists( userGroupPredicate.apply( root ) ),
        builder.exists( userPredicate.apply( root ) ) ) );

    return predicates;
}
 
Example 19
Source File: SecuredSpecifications.java    From abixen-platform with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static <T> Specification<T> getSpecification(final User user, final AclClassName aclClassName, final PermissionName permissionName) {
    log.debug("getSpecification() - user.id: {}, aclClassName: {}, permissionName: {}", user.getId(), aclClassName, permissionName);

    final String rolesField = "roles";
    final String permissionsField = "permissions";
    final String idField = "id";
    final String createdByField = "createdBy";
    final String permissionNameField = "permissionName";
    final String permissionField = "permission";
    final String aclSidField = "aclSid";
    final String sidTypeField = "sidType";
    final String sidIdField = "sidId";
    final String aclObjectIdentityField = "aclObjectIdentity";
    final String aclClassField = "aclClass";
    final String aclClassNameField = "aclClassName";
    final String objectIdField = "objectId";

    return (candidateRoot, criteriaQuery, cb) -> {
        final List<Predicate> predicates = new ArrayList<>();

        final Subquery<Long> subQueryUserPermissionCheck = criteriaQuery.subquery(Long.class);
        final Root<User> userRoot = subQueryUserPermissionCheck.from(User.class);
        final Join<User, Role> userRole = userRoot.join(rolesField);
        final Join<Role, Permission> rolePermission = userRole.join(permissionsField);
        final List<Predicate> parametersUserPermissionCheck = new ArrayList<>();
        parametersUserPermissionCheck.add(cb.equal(userRoot.get(idField), user.getId()));
        parametersUserPermissionCheck.add(cb.equal(rolePermission.get(permissionNameField), permissionName));
        subQueryUserPermissionCheck
                .select(cb.count(userRoot))
                .where(cb.and(parametersUserPermissionCheck.toArray(new Predicate[parametersUserPermissionCheck.size()])));

        final Subquery<Long> subQueryAclEntryRoleCheck = criteriaQuery.subquery(Long.class);
        final Root<AclEntry> aclEntryRoleRoot = subQueryAclEntryRoleCheck.from(AclEntry.class);
        final List<Predicate> parametersAclEntryRoleCheck = new ArrayList<>();
        parametersAclEntryRoleCheck.add(cb.equal(aclEntryRoleRoot.get(permissionField).get(permissionNameField), permissionName));
        parametersAclEntryRoleCheck.add(cb.equal(aclEntryRoleRoot.get(aclSidField).get(sidTypeField), AclSidType.ROLE));
        final List<Long> roleIds = user.getRoles().stream().map(r -> r.getId()).collect(Collectors.toList());
        parametersAclEntryRoleCheck.add(aclEntryRoleRoot.get(aclSidField).get(sidIdField).in(roleIds));
        parametersAclEntryRoleCheck.add(cb.equal(aclEntryRoleRoot.get(aclObjectIdentityField).get(aclClassField).get(aclClassNameField), aclClassName));
        parametersAclEntryRoleCheck.add(cb.equal(aclEntryRoleRoot.get(aclObjectIdentityField).get(objectIdField), candidateRoot.get(idField)));
        subQueryAclEntryRoleCheck
                .select(cb.count(aclEntryRoleRoot))
                .where(cb.and(parametersAclEntryRoleCheck.toArray(new Predicate[parametersAclEntryRoleCheck.size()])));

        final Subquery<Long> subQueryAclEntryOwnerCheck = criteriaQuery.subquery(Long.class);
        final Root<AclEntry> aclEntryOwnerRoot = subQueryAclEntryOwnerCheck.from(AclEntry.class);
        final List<Predicate> parametersAclEntryOwnerCheck = new ArrayList<>();
        parametersAclEntryOwnerCheck.add(cb.equal(aclEntryOwnerRoot.get(permissionField).get(permissionNameField), permissionName));
        parametersAclEntryOwnerCheck.add(cb.equal(aclEntryOwnerRoot.get(aclSidField).get(sidTypeField), AclSidType.OWNER));
        final Long ownerId = 0L;
        parametersAclEntryOwnerCheck.add(aclEntryOwnerRoot.get(aclSidField).get(sidIdField).in(ownerId));
        parametersAclEntryOwnerCheck.add(cb.equal(aclEntryOwnerRoot.get(aclObjectIdentityField).get(aclClassField).get(aclClassNameField), aclClassName));
        parametersAclEntryOwnerCheck.add(cb.equal(aclEntryOwnerRoot.get(aclObjectIdentityField).get(objectIdField), candidateRoot.get(idField)));
        parametersAclEntryOwnerCheck.add(cb.equal(candidateRoot.get(createdByField), user));
        subQueryAclEntryOwnerCheck
                .select(cb.count(aclEntryOwnerRoot))
                .where(cb.and(parametersAclEntryOwnerCheck.toArray(new Predicate[parametersAclEntryOwnerCheck.size()])));

        final Long minLimitValue = 0L;
        predicates.add(cb.greaterThan(subQueryUserPermissionCheck, minLimitValue));
        predicates.add(cb.greaterThan(subQueryAclEntryRoleCheck, minLimitValue));
        predicates.add(cb.greaterThan(subQueryAclEntryOwnerCheck, minLimitValue));

        return cb.or(predicates.toArray(new Predicate[predicates.size()]));
    };
}
 
Example 20
Source File: ContestContestantHibernateDao.java    From judgels with GNU General Public License v2.0 3 votes vote down vote up
static CustomPredicateFilter<ContestModel> hasParticipatingContestant(String userJid) {
    return (cb, cq, root) -> {
        Subquery<ContestContestantModel> sq = cq.subquery(ContestContestantModel.class);
        Root<ContestContestantModel> subRoot = sq.from(ContestContestantModel.class);

        sq.where(
                cb.equal(subRoot.get(ContestContestantModel_.contestJid), root.get(ContestModel_.jid)),
                cb.equal(subRoot.get(ContestContestantModel_.userJid), userJid),
                cb.equal(subRoot.get(ContestContestantModel_.status), APPROVED.name()),
                cb.isNotNull(subRoot.get(ContestContestantModel_.finalRank)));
        sq.select(subRoot);

        return cb.exists(sq);
    };
}