Search in sources :

Example 1 with Subquery

use of javax.persistence.criteria.Subquery in project hibernate-orm by hibernate.

the class QueryStructure method getParameters.

// PARAMETERS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public Set<ParameterExpression<?>> getParameters() {
    final Set<ParameterExpression<?>> parameters = new LinkedHashSet<ParameterExpression<?>>();
    final ParameterRegistry registry = new ParameterRegistry() {

        public void registerParameter(ParameterExpression<?> parameter) {
            parameters.add(parameter);
        }
    };
    ParameterContainer.Helper.possibleParameter(selection, registry);
    ParameterContainer.Helper.possibleParameter(restriction, registry);
    ParameterContainer.Helper.possibleParameter(having, registry);
    if (subqueries != null) {
        for (Subquery subquery : subqueries) {
            ParameterContainer.Helper.possibleParameter(subquery, registry);
        }
    }
    // both group-by and having expressions can (though unlikely) contain parameters...
    ParameterContainer.Helper.possibleParameter(having, registry);
    if (groupings != null) {
        for (Expression<?> grouping : groupings) {
            ParameterContainer.Helper.possibleParameter(grouping, registry);
        }
    }
    return parameters;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ParameterExpression(javax.persistence.criteria.ParameterExpression) Subquery(javax.persistence.criteria.Subquery)

Example 2 with Subquery

use of javax.persistence.criteria.Subquery in project keycloak by keycloak.

the class JpaUserProvider method searchForUserStream.

@Override
public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<UserEntity> queryBuilder = builder.createQuery(UserEntity.class);
    Root<UserEntity> root = queryBuilder.from(UserEntity.class);
    List<Predicate> predicates = new ArrayList<>();
    List<Predicate> attributePredicates = new ArrayList<>();
    predicates.add(builder.equal(root.get("realmId"), realm.getId()));
    if (!session.getAttributeOrDefault(UserModel.INCLUDE_SERVICE_ACCOUNT, true)) {
        predicates.add(root.get("serviceAccountClientLink").isNull());
    }
    Join<Object, Object> federatedIdentitiesJoin = null;
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (value == null) {
            continue;
        }
        switch(key) {
            case UserModel.SEARCH:
                for (String stringToSearch : value.trim().split("\\s+")) {
                    predicates.add(builder.or(getSearchOptionPredicateArray(stringToSearch, builder, root)));
                }
                break;
            case USERNAME:
            case FIRST_NAME:
            case LAST_NAME:
            case EMAIL:
                if (Boolean.valueOf(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString()))) {
                    predicates.add(builder.equal(builder.lower(root.get(key)), value.toLowerCase()));
                } else {
                    predicates.add(builder.like(builder.lower(root.get(key)), "%" + value.toLowerCase() + "%"));
                }
                break;
            case EMAIL_VERIFIED:
                predicates.add(builder.equal(root.get(key), Boolean.parseBoolean(value.toLowerCase())));
                break;
            case UserModel.ENABLED:
                predicates.add(builder.equal(root.get(key), Boolean.parseBoolean(value)));
                break;
            case UserModel.IDP_ALIAS:
                if (federatedIdentitiesJoin == null) {
                    federatedIdentitiesJoin = root.join("federatedIdentities");
                }
                predicates.add(builder.equal(federatedIdentitiesJoin.get("identityProvider"), value));
                break;
            case UserModel.IDP_USER_ID:
                if (federatedIdentitiesJoin == null) {
                    federatedIdentitiesJoin = root.join("federatedIdentities");
                }
                predicates.add(builder.equal(federatedIdentitiesJoin.get("userId"), value));
                break;
            case UserModel.EXACT:
                break;
            // All unknown attributes will be assumed as custom attributes
            default:
                Join<UserEntity, UserAttributeEntity> attributesJoin = root.join("attributes", JoinType.LEFT);
                attributePredicates.add(builder.and(builder.equal(builder.lower(attributesJoin.get("name")), key.toLowerCase()), builder.equal(builder.lower(attributesJoin.get("value")), value.toLowerCase())));
                break;
        }
    }
    if (!attributePredicates.isEmpty()) {
        predicates.add(builder.and(attributePredicates.toArray(new Predicate[0])));
    }
    Set<String> userGroups = (Set<String>) session.getAttribute(UserModel.GROUPS);
    if (userGroups != null) {
        Subquery subquery = queryBuilder.subquery(String.class);
        Root<UserGroupMembershipEntity> from = subquery.from(UserGroupMembershipEntity.class);
        subquery.select(builder.literal(1));
        List<Predicate> subPredicates = new ArrayList<>();
        subPredicates.add(from.get("groupId").in(userGroups));
        subPredicates.add(builder.equal(from.get("user").get("id"), root.get("id")));
        Subquery subquery1 = queryBuilder.subquery(String.class);
        subquery1.select(builder.literal(1));
        Root from1 = subquery1.from(ResourceEntity.class);
        List<Predicate> subs = new ArrayList<>();
        Expression<String> groupId = from.get("groupId");
        subs.add(builder.like(from1.get("name"), builder.concat("group.resource.", groupId)));
        subquery1.where(subs.toArray(new Predicate[subs.size()]));
        subPredicates.add(builder.exists(subquery1));
        subquery.where(subPredicates.toArray(new Predicate[subPredicates.size()]));
        predicates.add(builder.exists(subquery));
    }
    queryBuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get(UserModel.USERNAME)));
    TypedQuery<UserEntity> query = em.createQuery(queryBuilder);
    UserProvider users = session.users();
    return closing(paginateQuery(query, firstResult, maxResults).getResultStream()).map(userEntity -> users.getUserById(realm, userEntity.getId()));
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) UserAttributeEntity(org.keycloak.models.jpa.entities.UserAttributeEntity) UserGroupMembershipEntity(org.keycloak.models.jpa.entities.UserGroupMembershipEntity) Set(java.util.Set) HashSet(java.util.HashSet) Root(javax.persistence.criteria.Root) ArrayList(java.util.ArrayList) Subquery(javax.persistence.criteria.Subquery) UserEntity(org.keycloak.models.jpa.entities.UserEntity) Predicate(javax.persistence.criteria.Predicate) UserProvider(org.keycloak.models.UserProvider) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with Subquery

use of javax.persistence.criteria.Subquery in project CzechIdMng by bcvsolutions.

the class RoleGuaranteeEvaluator method getPermissions.

@Override
public Set<String> getPermissions(IdmRole entity, AuthorizationPolicy policy) {
    Set<String> permissions = super.getPermissions(entity, policy);
    if (entity == null || entity.getId() == null || !securityService.isAuthenticated()) {
        return permissions;
    }
    // 
    IdmRoleGuaranteeFilter filter = new IdmRoleGuaranteeFilter();
    filter.setRole(entity.getId());
    filter.setGuarantee(securityService.getCurrentId());
    // by identity
    if (roleGuaranteeService.find(filter, PageRequest.of(0, 1)).getTotalElements() > 0) {
        permissions.addAll(policy.getPermissions());
        return permissions;
    }
    // 
    // by role
    IdmRoleGuaranteeRoleFilter filterRole = new IdmRoleGuaranteeRoleFilter();
    filterRole.setRole(entity.getId());
    Set<UUID> guaranteeRoles = roleGuaranteeRoleService.find(filterRole, null).getContent().stream().map(rg -> rg.getGuaranteeRole()).collect(Collectors.toSet());
    // TODO: create some subquery ...
    if (identityRoleService.findValidRoles(securityService.getCurrentId(), null).getContent().stream().filter(ir -> guaranteeRoles.contains(ir.getRole())).findFirst().orElse(null) != null) {
        permissions.addAll(policy.getPermissions());
    }
    // 
    return permissions;
}
Also used : IdmIdentityRole_(eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole_) Autowired(org.springframework.beans.factory.annotation.Autowired) SecurityService(eu.bcvsolutions.idm.core.security.api.service.SecurityService) IdmIdentityRole(eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole) Predicate(javax.persistence.criteria.Predicate) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Root(javax.persistence.criteria.Root) IdmRoleGuaranteeRole(eu.bcvsolutions.idm.core.model.entity.IdmRoleGuaranteeRole) IdmRoleGuaranteeRole_(eu.bcvsolutions.idm.core.model.entity.IdmRoleGuaranteeRole_) Description(org.springframework.context.annotation.Description) RepositoryUtils(eu.bcvsolutions.idm.core.api.utils.RepositoryUtils) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) IdmIdentityRoleService(eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService) IdmRoleGuaranteeRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeRoleFilter) AbstractEntity_(eu.bcvsolutions.idm.core.api.entity.AbstractEntity_) IdmRoleGuaranteeService(eu.bcvsolutions.idm.core.api.service.IdmRoleGuaranteeService) AuthorizationPolicy(eu.bcvsolutions.idm.core.security.api.domain.AuthorizationPolicy) Set(java.util.Set) PageRequest(org.springframework.data.domain.PageRequest) AbstractAuthorizationEvaluator(eu.bcvsolutions.idm.core.security.evaluator.AbstractAuthorizationEvaluator) UUID(java.util.UUID) IdmRoleGuaranteeRoleService(eu.bcvsolutions.idm.core.api.service.IdmRoleGuaranteeRoleService) AbstractAuthentication(eu.bcvsolutions.idm.core.security.api.domain.AbstractAuthentication) Collectors(java.util.stream.Collectors) IdmIdentityContract_(eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract_) IdmRoleGuarantee_(eu.bcvsolutions.idm.core.model.entity.IdmRoleGuarantee_) IdmRoleGuarantee(eu.bcvsolutions.idm.core.model.entity.IdmRoleGuarantee) Component(org.springframework.stereotype.Component) LocalDate(java.time.LocalDate) IdmIdentity_(eu.bcvsolutions.idm.core.model.entity.IdmIdentity_) IdmRoleGuaranteeFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeFilter) Subquery(javax.persistence.criteria.Subquery) IdmRole(eu.bcvsolutions.idm.core.model.entity.IdmRole) IdmRoleGuaranteeFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeFilter) IdmRoleGuaranteeRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeRoleFilter) UUID(java.util.UUID)

Example 4 with Subquery

use of javax.persistence.criteria.Subquery in project CzechIdMng by bcvsolutions.

the class AbstractFormValueEvaluator method getPredicate.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate getPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder, AuthorizationPolicy policy, BasePermission... permission) {
    if (!hasPermission(policy, permission)) {
        return null;
    }
    if (!securityService.isAuthenticated()) {
        return null;
    }
    // 
    List<Predicate> predicates = new ArrayList<>();
    // 
    // by form definition
    IdmFormDefinitionDto formDefinition = getFormDefinition(policy);
    if (formDefinition == null) {
        // if form definition is empty ... we disable all
        return builder.disjunction();
    }
    // prevent to generate cross joins by default
    Join<T, IdmFormAttribute> eavAttr = root.join(AbstractFormValue_.formAttribute);
    Join<IdmFormAttribute, IdmFormDefinition> extDef = eavAttr.join(IdmFormAttribute_.formDefinition);
    // 
    predicates.add(builder.equal(extDef.get(IdmFormDefinition_.id), formDefinition.getId()));
    // 
    // by form attributes
    Set<String> formAttributes = getFormAttributes(policy);
    if (!formAttributes.isEmpty()) {
        predicates.add(eavAttr.get(IdmFormAttribute_.code).in(formAttributes));
    }
    // by self
    if (isSelfOnly(policy)) {
        predicates.add(builder.equal(root.get(FormValueService.PROPERTY_OWNER).get(BaseEntity.PROPERTY_ID), securityService.getCurrentId()));
    }
    // owner read or update - reuse the same subquery
    if (isOwnerRead(policy) || isOwnerUpdate(policy)) {
        Class<? extends FormableEntity> ownerType = getOwnerType();
        Subquery subquery = query.subquery(ownerType);
        Root subRoot = subquery.from(ownerType);
        // TODO: select 1 or something like this
        subquery.select(subRoot);
        subquery.where(builder.and(authorizationManager.getPredicate(subRoot, query, builder, isOwnerRead(policy) ? IdmBasePermission.READ : null, isOwnerUpdate(policy) ? IdmBasePermission.UPDATE : null), // correlation attribute
        builder.equal(root.get(FormValueService.PROPERTY_OWNER), subRoot)));
        // 
        // predicates.add(builder.greaterThan(builder.count(subquery), 0L));
        predicates.add(builder.exists(subquery));
    }
    // 
    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
}
Also used : Root(javax.persistence.criteria.Root) ArrayList(java.util.ArrayList) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) IdmFormAttribute(eu.bcvsolutions.idm.core.eav.entity.IdmFormAttribute) IdmFormDefinition(eu.bcvsolutions.idm.core.eav.entity.IdmFormDefinition) Subquery(javax.persistence.criteria.Subquery) Predicate(javax.persistence.criteria.Predicate)

Example 5 with Subquery

use of javax.persistence.criteria.Subquery in project ArachneCentralAPI by OHDSI.

the class BaseDataSourceServiceImpl method suggestDataSource.

@Override
public Page<DS> suggestDataSource(final String query, final Long studyId, final Long userId, PageRequest pageRequest) {
    List<DataSourceStatus> BAD_STATUSES = Arrays.asList(DataSourceStatus.DELETED, DataSourceStatus.DECLINED);
    final String[] split = query.trim().split(" ");
    CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<DS> cq = cb.createQuery(getType());
    Root<DS> root = cq.from(getType());
    Subquery sq = cq.subquery(Long.class);
    Root<StudyDataSourceLink> dsLink = sq.from(StudyDataSourceLink.class);
    sq.select(dsLink.get("dataSource").get("id"));
    sq.where(cb.and(cb.equal(dsLink.get("study").get("id"), studyId), cb.not(dsLink.get("status").in(BAD_STATUSES))));
    cq.select(root);
    // TRUE
    Predicate nameClause = cb.conjunction();
    if (split.length > 1 || (split.length == 1 && !split[0].equals(""))) {
        List<Predicate> predictList = new ArrayList<>();
        for (String one : split) {
            predictList.add(cb.like(cb.lower(root.get("name")), "%" + one.toLowerCase() + "%"));
            predictList.add(cb.like(cb.lower(root.get("dataNode").get("name")), "%" + one.toLowerCase() + "%"));
        }
        nameClause = cb.or(predictList.toArray(new Predicate[] {}));
    }
    cq.where(cb.and(cb.not(root.get("id").in(sq)), nameClause, cb.isNull(root.get("deleted")), cb.isTrue(root.get("published")), cb.isFalse(root.get("dataNode").get("virtual"))));
    TypedQuery<DS> typedQuery = this.entityManager.createQuery(cq);
    List<DS> list = typedQuery.setFirstResult((int) pageRequest.getOffset()).setMaxResults(pageRequest.getPageSize()).getResultList();
    return new PageImpl<>(list, pageRequest, list.size());
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) PageImpl(org.springframework.data.domain.PageImpl) StudyDataSourceLink(com.odysseusinc.arachne.portal.model.StudyDataSourceLink) ArrayList(java.util.ArrayList) Subquery(javax.persistence.criteria.Subquery) Predicate(javax.persistence.criteria.Predicate) DataSourceStatus(com.odysseusinc.arachne.portal.model.DataSourceStatus)

Aggregations

Subquery (javax.persistence.criteria.Subquery)8 Predicate (javax.persistence.criteria.Predicate)5 Root (javax.persistence.criteria.Root)5 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)4 ArrayList (java.util.ArrayList)3 Set (java.util.Set)2 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)2 DataSourceStatus (com.odysseusinc.arachne.portal.model.DataSourceStatus)1 StudyDataSourceLink (com.odysseusinc.arachne.portal.model.StudyDataSourceLink)1 AutomaticRoleAttributeRuleComparison (eu.bcvsolutions.idm.core.api.domain.AutomaticRoleAttributeRuleComparison)1 IdmRoleGuaranteeFilter (eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeFilter)1 IdmRoleGuaranteeRoleFilter (eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeRoleFilter)1 AbstractEntity_ (eu.bcvsolutions.idm.core.api.entity.AbstractEntity_)1 IdmIdentityRoleService (eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService)1 IdmRoleGuaranteeRoleService (eu.bcvsolutions.idm.core.api.service.IdmRoleGuaranteeRoleService)1 IdmRoleGuaranteeService (eu.bcvsolutions.idm.core.api.service.IdmRoleGuaranteeService)1 RepositoryUtils (eu.bcvsolutions.idm.core.api.utils.RepositoryUtils)1 IdmFormAttributeDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto)1 IdmFormDefinitionDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto)1 IdmFormAttribute (eu.bcvsolutions.idm.core.eav.entity.IdmFormAttribute)1