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;
}
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()));
}
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;
}
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()]));
}
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());
}
Aggregations