Java Examples for javax.persistence.criteria.Predicate

The following java examples will help you to understand the usage of javax.persistence.criteria.Predicate. These source code samples are taken from different open source projects.

Example 1
Project: ambari-master  File: StageDAO.java View source code
/**
   * Finds all {@link org.apache.ambari.server.orm.entities.StageEntity} that match the provided
   * {@link org.apache.ambari.server.controller.spi.Predicate}. This method will make JPA do the heavy lifting
   * of providing a slice of the result set.
   *
   * @param request
   * @return
   */
@RequiresSession
public List<StageEntity> findAll(Request request, Predicate predicate) {
    EntityManager entityManager = entityManagerProvider.get();
    // convert the Ambari predicate into a JPA predicate
    StagePredicateVisitor visitor = new StagePredicateVisitor();
    PredicateHelper.visit(predicate, visitor);
    CriteriaQuery<StageEntity> query = visitor.getCriteriaQuery();
    javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();
    if (jpaPredicate != null) {
        query.where(jpaPredicate);
    }
    // sorting
    JpaSortBuilder<StageEntity> sortBuilder = new JpaSortBuilder<>();
    List<Order> sortOrders = sortBuilder.buildSortOrders(request.getSortRequest(), visitor);
    query.orderBy(sortOrders);
    TypedQuery<StageEntity> typedQuery = entityManager.createQuery(query);
    // !!! https://bugs.eclipse.org/bugs/show_bug.cgi?id=398067
    // ensure that an associated entity with a JOIN is not stale; this causes
    // the associated StageEntity to be stale
    typedQuery.setHint(QueryHints.REFRESH, HintValues.TRUE);
    return daoUtils.selectList(typedQuery);
}
Example 2
Project: kylo-master  File: FeedAclIndexQueryAugmentor.java View source code
@Override
public <S, T, ID extends Serializable> Specification<S> augment(Specification<S> spec, Class<S> domainClass, JpaEntityInformation<T, ID> entityInformation) {
    LOG.debug("QueryAugmentor.augment");
    return ( root,  query,  criteriaBuilder) -> {
        Root<JpaFeedOpsAclEntry> fromAcl = query.from(JpaFeedOpsAclEntry.class);
        query.distinct(true);
        if (query.getSelection() == null) {
            query.select((Selection) root);
        }
        Path<Object> feedId = getFeedId(entityInformation, root);
        javax.persistence.criteria.Predicate rootFeedIdEqualToAclFeedId = criteriaBuilder.equal(feedId, fromAcl.get("feedId"));
        RoleSetExposingSecurityExpressionRoot userCxt = getUserContext();
        javax.persistence.criteria.Predicate aclPrincipalInGroups = fromAcl.get("principalName").in(userCxt.getGroups());
        javax.persistence.criteria.Predicate aclPrincipalTypeIsGroup = criteriaBuilder.equal(fromAcl.get("principalType"), PrincipalType.GROUP);
        javax.persistence.criteria.Predicate acePrincipalGroupMatch = criteriaBuilder.and(aclPrincipalInGroups, aclPrincipalTypeIsGroup);
        javax.persistence.criteria.Predicate aclPrincipalEqUser = criteriaBuilder.equal(fromAcl.get("principalName"), userCxt.getName());
        javax.persistence.criteria.Predicate aclPrincipalTypeIsUser = criteriaBuilder.equal(fromAcl.get("principalType"), PrincipalType.USER);
        javax.persistence.criteria.Predicate acePrincipalUserMatch = criteriaBuilder.and(aclPrincipalEqUser, aclPrincipalTypeIsUser);
        javax.persistence.criteria.Predicate acePrincipalMatch = criteriaBuilder.or(acePrincipalGroupMatch, acePrincipalUserMatch);
        javax.persistence.criteria.Predicate feedIdEqualsAndPrincipalMatch = criteriaBuilder.and(rootFeedIdEqualToAclFeedId, acePrincipalMatch);
        if (spec != null) {
            javax.persistence.criteria.Predicate predicate = spec.toPredicate(root, query, criteriaBuilder);
            return criteriaBuilder.and(predicate, feedIdEqualsAndPrincipalMatch);
        } else {
            return feedIdEqualsAndPrincipalMatch;
        }
    };
}
Example 3
Project: brix-cms-plugins-master  File: GridDataSource.java View source code
private void applyFilter(CriteriaBuilder builder, CriteriaQuery<?> criteriaQuery, Root<T> root) {
    for (FilterPluginEntry<T, ID, F> filterEntry : filters) {
        List<Predicate> predicates = filterEntry.getPlugin().createPredicate(builder, root, filterEntry.getFilter());
        if (!predicates.isEmpty()) {
            criteriaQuery.where(builder.and(predicates.toArray(new Predicate[0])));
        }
    }
}
Example 4
Project: dg-toolkit-master  File: TestFormFilterState.java View source code
@Override
public Specification<TestForm> getSpecification() {
    return ( root,  query,  cb) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(textField)) {
            predicates.add(cb.like(root.get(TestForm_.textField), "%" + textField + "%"));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
Example 5
Project: GT-FHIR-master  File: PatientFhirResourceDao.java View source code
@Override
public Predicate translatePredicateString(Class<? extends IResourceEntity> entity, String theParamName, String likeExpression, From<? extends IResourceEntity, ? extends IResourceEntity> from, CriteriaBuilder theBuilder) {
    Predicate singleCode = null;
    switch(theParamName) {
        case Patient.SP_ADDRESS:
            Predicate lc1 = theBuilder.like(from.get("location").get("address1").as(String.class), likeExpression);
            Predicate lc2 = theBuilder.like(from.get("location").get("address2").as(String.class), likeExpression);
            Predicate lc3 = theBuilder.like(from.get("location").get("city").as(String.class), likeExpression);
            Predicate lc4 = theBuilder.like(from.get("location").get("state").as(String.class), likeExpression);
            Predicate lc5 = theBuilder.like(from.get("location").get("zipCode").as(String.class), likeExpression);
            Predicate lc6 = theBuilder.like(from.get("location").get("country").as(String.class), likeExpression);
            singleCode = theBuilder.or(lc1, lc2, lc3, lc4, lc5, lc6);
            break;
        case Patient.SP_GIVEN:
            Predicate gn1 = theBuilder.like(from.get("givenName1").as(String.class), likeExpression);
            Predicate gn2 = theBuilder.like(from.get("givenName2").as(String.class), likeExpression);
            singleCode = theBuilder.or(gn1, gn2);
            break;
        case Patient.SP_FAMILY:
            singleCode = theBuilder.like(from.get("familyName").as(String.class), likeExpression);
            break;
        case Patient.SP_NAME:
            gn1 = theBuilder.like(from.get("givenName1").as(String.class), likeExpression);
            gn2 = theBuilder.like(from.get("givenName2").as(String.class), likeExpression);
            Predicate fn1 = theBuilder.like(from.get("familyName").as(String.class), likeExpression);
            Predicate n1 = theBuilder.like(from.get("prefixName").as(String.class), likeExpression);
            Predicate n2 = theBuilder.like(from.get("suffixName").as(String.class), likeExpression);
            singleCode = theBuilder.or(gn1, gn2, fn1, n1, n2);
            break;
        default:
            break;
    }
    return singleCode;
}
Example 6
Project: iBeaconServer-master  File: BeaconSpecs.java View source code
/**
     * Creates the Beacon search specification from the given attributes
     *
     * @param username
     *         The username to filter the results by. Could be NULL for API queries.
     * @param projectId
     *         The project ID to filter the results by. Could be NULL for API queries.
     * @param regionId
     *         The region ID to filter the results by. Could be NULL for API queries.
     * @param uuid
     *         The UUID attribute to filter the results by.
     * @param major
     *         The major attribute to filter the results by.
     * @param minor
     *         The minor attribute to filter the results by.
     * @param designated
     *         The designated attribute to filter the results by.
     *
     * @return The specification of the beacon
     */
public static Specification<Beacon> beaconWithSpecification(final String username, final Long projectId, final Long regionId, final String uuid, final Integer major, final Integer minor, final Boolean designated) {
    return ( root,  query,  builder) -> {
        ArrayList<Predicate> predicates = new ArrayList<Predicate>();
        if (username != null) {
            predicates.add(builder.equal(root.get("region").get("project").get("owner").get("username").as(String.class), username));
        }
        if (projectId != null) {
            predicates.add(builder.equal(root.get("region").get("project").get("projectId"), projectId));
        }
        if (regionId != null) {
            predicates.add(builder.equal(root.get("region").get("regionId"), regionId));
        }
        if (uuid != null && !uuid.equals("")) {
            if (uuid.length() == Beacon.UUID_MAX_LENGTH) {
                predicates.add(builder.equal(root.get("uuid"), uuid.toUpperCase()));
            } else {
                predicates.add(builder.like(root.get("uuid").as(String.class), "%" + uuid.toUpperCase() + "%"));
            }
        }
        if (major != null && !major.equals(-1)) {
            predicates.add(builder.equal(root.get("major"), major));
        }
        if (minor != null && !minor.equals(-1)) {
            predicates.add(builder.equal(root.get("minor"), minor));
        }
        if (designated != null) {
            predicates.add(builder.equal(root.get("designated").as(Boolean.class), designated));
        }
        return builder.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
Example 7
Project: spring-data-jpa-examples-master  File: PersonSpecifications.java View source code
/**
     * Creates a specification used to find persons whose last name begins with
     * the given search term. This search is case insensitive.
     * @param searchTerm
     * @return
     */
public static Specification<Person> lastNameIsLike(final String searchTerm) {
    return new Specification<Person>() {

        @Override
        public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) {
            String likePattern = getLikePattern(searchTerm);
            return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern);
        }

        private String getLikePattern(final String searchTerm) {
            StringBuilder pattern = new StringBuilder();
            pattern.append(searchTerm.toLowerCase());
            pattern.append("%");
            return pattern.toString();
        }
    };
}
Example 8
Project: suitegda-master  File: Login.java View source code
@Override
public void accept() {
    Database db = (Database) Register.queryUtility(IDatabase.class);
    EntityManager em = db.getEntityManagerFactory().createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object> cq = cb.createQuery();
    Root from = cq.from(Utente.class);
    cq.select(from);
    Predicate predicate = cb.equal(from.get("login"), this.username.text().toLowerCase());
    cq = cq.where(predicate);
    Query q = em.createQuery(cq);
    List entities = q.getResultList();
    if (entities.size() == 1) {
        utente = (Utente) entities.get(0);
        String pwd = this.password.text();
        ICheckLogin checkLogin = (ICheckLogin) Register.queryUtility(ICheckLogin.class);
        if (checkLogin != null) {
            if (checkLogin.check(this.username.text(), this.password.text())) {
                Register.registerUtility(utente, IUtente.class);
                super.accept();
                return;
            }
        } else {
            if (SuiteUtil.digest(pwd).equals(utente.getPassword())) {
                Register.registerUtility(utente, IUtente.class);
                super.accept();
                return;
            }
        }
    }
    QMessageBox.critical(this, "Utente o password errati", "Il nome utente o la password risultano errati.");
}
Example 9
Project: TechnologyReadinessTool-master  File: OrgPartTaskItemProviderImpl.java View source code
private TypedQuery<OrgPartDO> getQuery() {
    CriteriaQuery<OrgPartDO> query = em.getCriteriaBuilder().createQuery(OrgPartDO.class);
    Root<OrgPartDO> orgPart = query.from(OrgPartDO.class);
    orgPart.fetch(OrgPartDO_.org);
    Predicate scopeClause = em.getCriteriaBuilder().equal(orgPart.get(OrgPartDO_.scope).get(ScopeDO_.scopeId), scope.getScopeId());
    In<Long> inOrg = em.getCriteriaBuilder().in(orgPart.get(OrgPartDO_.org).get(OrgDO_.orgId));
    if (orgs.isEmpty()) {
        throw new IllegalStateException("No organizations are selected.");
    }
    for (Org org : orgs) {
        inOrg.value(org.getOrgId());
    }
    query.where(scopeClause, inOrg);
    return em.createQuery(query);
}
Example 10
Project: VaadinUtils-master  File: SimplePredicate.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Predicate getPredicate(CriterBuilder<ROOT> builder, CriteriaBuilder criteriaBuilder, Map<Class<?>, Join<ROOT, ?>> joins) {
    Path<FIELD_TYPE> expr = null;
    Join<ROOT, ?> join = joins.get(field.getDeclaringType().getJavaType());
    if (join == null) {
        expr = builder.entityRoot.get((SingularAttribute) field);
    } else {
        expr = join.get((SingularAttribute) field);
    }
    return createPredicate(criteriaBuilder, expr, value);
}
Example 11
Project: eclipselink.runtime-master  File: ExpressionImpl.java View source code
/**
     * Apply a predicate to test whether the expression is a member
     * of the argument list.
     * @param values
     * @return predicate testing for membership
     */
public Predicate in(Expression<?>... values) {
    if (values != null) {
        List list = new ArrayList();
        list.add(this);
        if (values.length == 1 && ((InternalExpression) values[0]).isSubquery()) {
            list.add(values[0]);
            return new CompoundExpressionImpl(this.metamodel, this.currentNode.in(((SubQueryImpl) values[0]).subQuery), list, "in");
        } else {
            List<Object> inValues = new ArrayList<Object>();
            for (Expression exp : values) {
                if (!((InternalExpression) exp).isLiteral() && !((InternalExpression) exp).isParameter()) {
                    Object[] params = new Object[] { exp };
                    throw new IllegalArgumentException(ExceptionLocalization.buildMessage("CRITERIA_NON_LITERAL_PASSED_TO_IN", params));
                } else {
                    list.add(exp);
                    inValues.add(((InternalSelection) exp).getCurrentNode());
                }
            }
            return new CompoundExpressionImpl(this.metamodel, this.currentNode.in(inValues), list, "in");
        }
    }
    throw new IllegalArgumentException(ExceptionLocalization.buildMessage("NULL_PASSED_TO_EXPRESSION_IN"));
}
Example 12
Project: Faktotum-master  File: BundesbruderDao.java View source code
/**
	 * Find Bundesbruder with the firstname, lastname or alias matching the
	 * search string
	 * 
	 * @param searchString
	 *            the search string
	 * @return a list of BundesbruderEntities matching the search
	 */
public List<BundesbruderEntity> findBySearchString(String searchString, boolean searchAlsoInAliases) {
    CriteriaBuilder criteriaBuilder = this.getCriteriaBuilder();
    CriteriaQuery<BundesbruderEntity> criteriaQuery = criteriaBuilder.createQuery(BundesbruderEntity.class);
    Root<BundesbruderEntity> entityRoot = criteriaQuery.from(BundesbruderEntity.class);
    ArrayList<Predicate> predicatesForOrStatement = new ArrayList<>();
    predicatesForOrStatement.add(criteriaBuilder.like(criteriaBuilder.lower(entityRoot.get(BundesbruderEntity_.firstName)), "%" + searchString.toLowerCase() + "%"));
    predicatesForOrStatement.add(criteriaBuilder.like(criteriaBuilder.lower(entityRoot.get(BundesbruderEntity_.lastName)), "%" + searchString.toLowerCase() + "%"));
    if (searchAlsoInAliases) {
        predicatesForOrStatement.add(criteriaBuilder.like(criteriaBuilder.lower(entityRoot.get(BundesbruderEntity_.alias)), "%" + searchString.toLowerCase() + "%"));
    }
    criteriaQuery.where(criteriaBuilder.or(predicatesForOrStatement.toArray(new Predicate[predicatesForOrStatement.size()])));
    TypedQuery<BundesbruderEntity> typedQuery = this.createQuery(criteriaQuery);
    try {
        List<BundesbruderEntity> searchResult = typedQuery.getResultList();
        return searchResult;
    } catch (NoResultException e) {
        this.getLogger().log(Level.FINE, "Bundesbruder for search String " + searchString + " not in DB", e);
        return null;
    }
}
Example 13
Project: Broadleaf-eCommerce-master  File: ResourcePurgeDaoImpl.java View source code
protected <T> TypedQuery<T> buildCustomerQuery(Date dateCreatedMinThreshold, Boolean registered, Boolean deactivated, Boolean isPreview, Class<T> returnType) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(returnType);
    Root<CustomerImpl> root = criteria.from(CustomerImpl.class);
    if (Long.class.equals(returnType)) {
        criteria.select((Selection<? extends T>) builder.count(root));
    } else {
        criteria.select((Selection<? extends T>) root);
    }
    //find only customers that do not have any orders, otherwise a purge would fail because of referential integrity
    Subquery<Long> subquery = criteria.subquery(Long.class);
    Root orderRoot = subquery.from(OrderImpl.class);
    subquery.select(builder.count(orderRoot));
    subquery.where(builder.equal(orderRoot.get("customer"), root));
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(subquery, 0L));
    if (registered != null) {
        if (registered) {
            restrictions.add(builder.isTrue(root.get("registered").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("registered")), builder.isFalse(root.get("registered").as(Boolean.class))));
        }
    }
    if (deactivated != null) {
        if (deactivated) {
            restrictions.add(builder.isTrue(root.get("deactivated").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("deactivated")), builder.isFalse(root.get("deactivated").as(Boolean.class))));
        }
    }
    if (dateCreatedMinThreshold != null) {
        restrictions.add(builder.lessThan(root.get("auditable").get("dateCreated").as(Date.class), dateCreatedMinThreshold));
    }
    if (isPreview != null) {
        if (isPreview) {
            restrictions.add(builder.isTrue(root.get("previewable").get("isPreview").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("previewable").get("isPreview")), builder.isFalse(root.get("previewable").get("isPreview").as(Boolean.class))));
        }
    }
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    return em.createQuery(criteria);
}
Example 14
Project: BroadleafCommerce-master  File: ResourcePurgeDaoImpl.java View source code
protected <T> TypedQuery<T> buildCustomerQuery(Date dateCreatedMinThreshold, Boolean registered, Boolean deactivated, Boolean isPreview, Class<T> returnType) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(returnType);
    Root<CustomerImpl> root = criteria.from(CustomerImpl.class);
    if (Long.class.equals(returnType)) {
        criteria.select((Selection<? extends T>) builder.count(root));
    } else {
        criteria.select((Selection<? extends T>) root);
    }
    //find only customers that do not have any orders, otherwise a purge would fail because of referential integrity
    Subquery<Long> subquery = criteria.subquery(Long.class);
    Root orderRoot = subquery.from(OrderImpl.class);
    subquery.select(builder.count(orderRoot));
    subquery.where(builder.equal(orderRoot.get("customer"), root));
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(subquery, 0L));
    if (registered != null) {
        if (registered) {
            restrictions.add(builder.isTrue(root.get("registered").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("registered")), builder.isFalse(root.get("registered").as(Boolean.class))));
        }
    }
    if (deactivated != null) {
        if (deactivated) {
            restrictions.add(builder.isTrue(root.get("deactivated").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("deactivated")), builder.isFalse(root.get("deactivated").as(Boolean.class))));
        }
    }
    if (dateCreatedMinThreshold != null) {
        restrictions.add(builder.lessThan(root.get("auditable").get("dateCreated").as(Date.class), dateCreatedMinThreshold));
    }
    if (isPreview != null) {
        if (isPreview) {
            restrictions.add(builder.isTrue(root.get("previewable").get("isPreview").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("previewable").get("isPreview")), builder.isFalse(root.get("previewable").get("isPreview").as(Boolean.class))));
        }
    }
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    return em.createQuery(criteria);
}
Example 15
Project: commerce-master  File: ResourcePurgeDaoImpl.java View source code
protected <T> TypedQuery<T> buildCustomerQuery(Date dateCreatedMinThreshold, Boolean registered, Boolean deactivated, Boolean isPreview, Class<T> returnType) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(returnType);
    Root<CustomerImpl> root = criteria.from(CustomerImpl.class);
    if (Long.class.equals(returnType)) {
        criteria.select((Selection<? extends T>) builder.count(root));
    } else {
        criteria.select((Selection<? extends T>) root);
    }
    //find only customers that do not have any orders, otherwise a purge would fail because of referential integrity
    Subquery<Long> subquery = criteria.subquery(Long.class);
    Root orderRoot = subquery.from(OrderImpl.class);
    subquery.select(builder.count(orderRoot));
    subquery.where(builder.equal(orderRoot.get("customer"), root));
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(subquery, 0L));
    if (registered != null) {
        if (registered) {
            restrictions.add(builder.isTrue(root.get("registered").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("registered")), builder.isFalse(root.get("registered").as(Boolean.class))));
        }
    }
    if (deactivated != null) {
        if (deactivated) {
            restrictions.add(builder.isTrue(root.get("deactivated").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("deactivated")), builder.isFalse(root.get("deactivated").as(Boolean.class))));
        }
    }
    if (dateCreatedMinThreshold != null) {
        restrictions.add(builder.lessThan(root.get("auditable").get("dateCreated").as(Date.class), dateCreatedMinThreshold));
    }
    if (isPreview != null) {
        if (isPreview) {
            restrictions.add(builder.isTrue(root.get("previewable").get("isPreview").as(Boolean.class)));
        } else {
            restrictions.add(builder.or(builder.isNull(root.get("previewable").get("isPreview")), builder.isFalse(root.get("previewable").get("isPreview").as(Boolean.class))));
        }
    }
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    return em.createQuery(criteria);
}
Example 16
Project: gazpachoquest-master  File: PropertySelectorSpecification.java View source code
@Override
public Predicate toPredicate(Root<E> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (PropertySelector<?, ?> selector : sp.getProperties()) {
        if (selector.isBoolean()) {
            byBooleanSelector(root, builder, predicates, sp, (PropertySelector<? super E, Boolean>) selector);
        } else {
            byObjectSelector(root, builder, predicates, sp, (PropertySelector<? super E, ?>) selector);
        }
    }
    return JpaUtil.concatPredicate(sp, builder, predicates);
}
Example 17
Project: graniteds-master  File: FilterExampleSpecification.java View source code
private void applyAttributes(List<Predicate> predicates, Path<?> root, CriteriaBuilder builder, ManagedType<?> filterType, Object filter) {
    // Query by example : the filter is of the same type as the entity
    PropertyDescriptor[] pds = null;
    try {
        // Query by bean filter
        BeanInfo info = Introspector.getBeanInfo(filter.getClass());
        pds = info.getPropertyDescriptors();
    } catch (Exception e) {
        throw new RuntimeException("Could not introspect filter bean", e);
    }
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod().getDeclaringClass() == Object.class)
            continue;
        if (pd.getReadMethod().isAnnotationPresent(FilterMapping.class) && pd.getReadMethod().getAnnotation(FilterMapping.class).mode() == FilterMode.EXCLUDE)
            continue;
        Attribute<?, ?> attribute = null;
        try {
            attribute = filterType.getAttribute(pd.getName());
        } catch (IllegalArgumentException e) {
        }
        if (attribute == null)
            continue;
        if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
            // Visit embedded elements recursively
            try {
                Object embedded = pd.getReadMethod().invoke(filter);
                if (embedded != null) {
                    ManagedType<?> embeddedType = metamodel.embeddable(attribute.getJavaType());
                    applyAttributes(predicates, root.get(pd.getName()), builder, embeddedType, embedded);
                }
            } catch (Exception e) {
                throw new RuntimeException("Could not get filter property " + pd.getName(), e);
            }
            continue;
        }
        if (pd.getWriteMethod() == null || attribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.BASIC)
            continue;
        Object value = null;
        try {
            value = pd.getReadMethod().invoke(filter);
        } catch (Exception e) {
            throw new RuntimeException("Could not get filter property " + pd.getName(), e);
        }
        Predicate predicate = FilterSpecUtil.buildPredicate(root, builder, pd.getReadMethod().getReturnType(), pd.getName(), value);
        if (predicate != null)
            predicates.add(predicate);
    }
}
Example 18
Project: HERD-master  File: TagTypeDaoImpl.java View source code
@Override
public TagTypeEntity getTagTypeByDisplayName(String displayName) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TagTypeEntity> criteria = builder.createQuery(TagTypeEntity.class);
    // The criteria root is the tag type code.
    Root<TagTypeEntity> tagTypeEntity = criteria.from(TagTypeEntity.class);
    // Create the standard restrictions.
    Predicate queryRestriction = builder.equal(builder.upper(tagTypeEntity.get(TagTypeEntity_.displayName)), displayName.toUpperCase());
    // Add all clauses to the query.
    criteria.select(tagTypeEntity).where(queryRestriction);
    // Run the query and return the results.
    return executeSingleResultQuery(criteria, String.format("Found more than one tag type with displayName=\"%s\".", displayName));
}
Example 19
Project: jarchetypes-master  File: CRUDService.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> List<T> search(Class<T> entityClass, Map<String, Object> parameters) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery query = builder.createQuery();
    Root<?> root = query.from(entityClass);
    query.select(root);
    Predicate predicate = null;
    for (String field : parameters.keySet()) {
        Predicate p = builder.equal(root.get(field), parameters.get(field));
        predicate = predicate == null ? p : builder.and(predicate, p);
    }
    if (predicate != null)
        query.where(predicate);
    return em.createQuery(query).getResultList();
}
Example 20
Project: javaee-addon-master  File: SimpleStringFilterTranslatorTest.java View source code
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testTranslate() {
    SimpleStringFilter filter = new SimpleStringFilter("firstName", "Thomas", false, false);
    Path path = mock(Path.class);
    Expression<String> upper = mock(Expression.class);
    CriteriaBuilder builder = mock(CriteriaBuilder.class);
    when(builder.upper(path)).thenReturn(upper);
    Root<PersistentEntity> root = mock(Root.class);
    when(root.get("firstName")).thenReturn(path);
    Predicate predicate = mock(Predicate.class);
    when(builder.like(path, "%Thomas%")).thenReturn(predicate);
    Predicate translate = translator.translate(filter, builder, root, null);
    assertEquals(predicate, translate);
}
Example 21
Project: jdal-master  File: BookCriteriaBuilder.java View source code
/**
	 * {@inheritDoc}
	 */
public CriteriaQuery<Book> build(CriteriaQuery<Book> criteria, CriteriaBuilder cb, Filter filter) {
    BookFilter f = (BookFilter) filter;
    Root<Book> root = criteria.from(Book.class);
    Path<Author> author = root.<Author>get("author");
    Path<Category> category = root.<Category>get("category");
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (StringUtils.isNotEmpty(f.getName()))
        predicates.add(cb.like(root.<String>get("name"), f.getName()));
    if (f.getCategory() != null)
        predicates.add(cb.equal(category.<String>get("name"), f.getCategory().getName()));
    if (f.getBefore() != null)
        predicates.add(cb.lessThanOrEqualTo(root.<Date>get("publishedDate"), f.getBefore()));
    if (f.getAfter() != null)
        predicates.add(cb.greaterThanOrEqualTo(root.<Date>get("publishedDate"), f.getAfter()));
    if (StringUtils.isNotEmpty(f.getAuthorName()))
        predicates.add(cb.like(author.<String>get("name"), f.getAuthorName()));
    if (StringUtils.isNotEmpty(f.getAuthorSurname()))
        predicates.add(cb.like(author.<String>get("surname"), f.getAuthorSurname()));
    if (StringUtils.isNotEmpty(f.getIsbn()))
        predicates.add(cb.like(root.<String>get("isbn"), f.getIsbn()));
    if (predicates.size() > 0)
        criteria.where(cb.and(predicates.toArray(new Predicate[] {})));
    return criteria;
}
Example 22
Project: jpasearch-master  File: JpaUtil.java View source code
public Predicate andPredicate(CriteriaBuilder builder, Iterable<Predicate> predicatesNullAllowed) {
    List<Predicate> predicates = newArrayList(filter(predicatesNullAllowed, notNull()));
    if ((predicates == null) || predicates.isEmpty()) {
        return null;
    } else if (predicates.size() == 1) {
        return predicates.get(0);
    } else {
        return builder.and(toArray(predicates, Predicate.class));
    }
}
Example 23
Project: ngrinder-master  File: PerfTestSpecification.java View source code
/**
	 * Get the {@link Specification} checking if the {@link PerfTest#getTags()} has the given tagValue.
	 *
	 * @param tagValue tagValue
	 * @return {@link Specification}
	 */
public static Specification<PerfTest> hasTag(final String tagValue) {
    return new Specification<PerfTest>() {

        @Override
        public Predicate toPredicate(Root<PerfTest> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            SetJoin<Object, Object> join = root.joinSet("tags");
            return cb.equal(join.get("tagValue"), tagValue);
        }
    };
}
Example 24
Project: park_java-master  File: AdornedTargetListPersistenceModuleEx.java View source code
@Override
public List<FilterMapping> getAdornedTargetFilterMappings(PersistencePerspective persistencePerspective, CriteriaTransferObject cto, Map<String, FieldMetadata> mergedProperties, AdornedTargetList adornedTargetList) throws ClassNotFoundException {
    List<FilterMapping> mappings = super.getAdornedTargetFilterMappings(persistencePerspective, cto, mergedProperties, adornedTargetList);
    Class<?> clazz = null;
    try {
        clazz = getLocationBasedClass(adornedTargetList);
    } catch (ServiceException e) {
        throw new RuntimeException(e);
    }
    if (clazz != null) {
        AdminUser adminUser = securityVerifier.getPersistentAdminUser();
        if (adminUser instanceof MyAdminUser) {
            FilterMapping filterMapping2 = new FilterMapping().withFieldPath(new FieldPath().withTargetProperty("location.id")).withFilterValues(Arrays.asList(String.valueOf(((MyAdminUser) adminUser).getFulfillmentLocation().getId()))).withRestriction(new Restriction().withPredicateProvider(new PredicateProvider<Serializable, String>() {

                @Override
                public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path<Serializable> explicitPath, List<String> directValues) {
                    if (String.class.isAssignableFrom(explicitPath.getJavaType())) {
                        return builder.equal(explicitPath, directValues.get(0));
                    } else {
                        return builder.equal(explicitPath, Long.parseLong(directValues.get(0)));
                    }
                }
            }));
            mappings.add(filterMapping2);
        }
    }
    return mappings;
}
Example 25
Project: Sparqlify-master  File: EntityRefUtils.java View source code
@SuppressWarnings("rawtypes")
public static CriteriaQuery<?> toCriteria(EntityManager em, EntityRef entityRef) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    Class<?> entityClass = entityRef.getEntityClass();
    CriteriaQuery cq = cb.createQuery(entityClass);
    @SuppressWarnings("unchecked") Root r = cq.from(entityClass);
    Map<String, Object> map = entityRef.getPropertyToValue();
    List<Predicate> predicates = new ArrayList<Predicate>(map.size());
    for (Entry<String, Object> entry : map.entrySet()) {
        String propertyName = entry.getKey();
        Object value = entry.getValue();
        Predicate predicate = cb.equal(r.get(propertyName), value);
        predicates.add(predicate);
    }
    cq.where(predicates.toArray(new Predicate[0]));
    @SuppressWarnings("unchecked") CriteriaQuery result = cq.select(r);
    return result;
//List<ConfigToExecution> result = em.createQuery(cq).getResultList();
}
Example 26
Project: spring-data-examples-master  File: CustomerSpecifications.java View source code
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    Root<Account> accounts = query.from(Account.class);
    Path<Date> expiryDate = accounts.<Date>get("expiryDate");
    Predicate customerIsAccountOwner = cb.equal(accounts.<Customer>get("customer"), root);
    Predicate accountExpiryDateBefore = cb.lessThan(expiryDate, date.toDateTimeAtStartOfDay().toDate());
    return cb.and(customerIsAccountOwner, accountExpiryDateBefore);
}
Example 27
Project: spring4-sandbox-master  File: JpaSpecs.java View source code
public static Specification<Conference> inProgressConferences() {
    return new Specification<Conference>() {

        @Override
        public Predicate toPredicate(Root<Conference> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Expression<Timestamp> currentTimestamp = cb.currentTimestamp();
            return cb.and(cb.greaterThan(root.get("endedDate").as(Date.class), currentTimestamp), cb.lessThan(root.get("startedDate").as(Date.class), currentTimestamp));
        }
    };
}
Example 28
Project: Struts2-Rest-Jpa-BootStap-master  File: JpaCustomerDAO.java View source code
/**
	 * Search by Customer example
	 */
public List<Customer> search(final Customer element) {
    final EntityManager em = getEntityManager();
    if (element != null) {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Customer> criteriaQuery = criteriaBuilder.createQuery(Customer.class);
        Root<Customer> from = criteriaQuery.from(Customer.class);
        List<Predicate> listP = new ArrayList<Predicate>();
        if (CoreUtils.isNotBlank(element.getCode())) {
            Predicate predicate = criteriaBuilder.equal(from.get("code"), element.getCode());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getCountryCode())) {
            Predicate predicate = criteriaBuilder.equal(from.get("countryCode"), element.getCountryCode());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getFirstName())) {
            Predicate predicate = criteriaBuilder.equal(from.get("firstName"), element.getFirstName());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getLastName())) {
            Predicate predicate = criteriaBuilder.equal(from.get("lastName"), element.getLastName());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getLogin())) {
            Predicate predicate = criteriaBuilder.equal(from.get("login"), element.getLogin());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getPassword())) {
            Predicate predicate = criteriaBuilder.equal(from.get("password"), element.getPassword());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getAge())) {
            Predicate predicate = criteriaBuilder.equal(from.get("age"), element.getAge());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getCity())) {
            Predicate predicate = criteriaBuilder.equal(from.get("city"), element.getCity());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getZipCode())) {
            Predicate predicate = criteriaBuilder.equal(from.get("zipCode"), element.getZipCode());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getPhone())) {
            Predicate predicate = criteriaBuilder.equal(from.get("phone"), element.getPhone());
            listP.add(predicate);
        }
        if (CoreUtils.isNotBlank(element.getReviewer())) {
            Predicate predicate = criteriaBuilder.equal(from.get("reviewer"), element.getReviewer());
            listP.add(predicate);
        }
        criteriaQuery.where(listP.toArray(ap));
        TypedQuery<Customer> tq = em.createQuery(criteriaQuery);
        return tq.getResultList();
    } else {
        return this.loadAll();
    }
}
Example 29
Project: tasq-master  File: TaskSpecification.java View source code
@Override
public Predicate toPredicate(Root<Task> task, CriteriaQuery<?> cq, CriteriaBuilder cb) {
    Predicate predicate = cb.conjunction();
    //project
    predicate = cb.and(predicate, cb.equal(task.get(Task_.project).get(Project_.id), taskFilter.getProject().getId()));
    //      no subtasks
    predicate = cb.and(predicate, task.get(Task_.parent).isNull());
    if (StringUtils.isNotBlank(taskFilter.getByState())) {
        if (TaskFilter.OPEN.equals(taskFilter.getByState())) {
            predicate = cb.and(predicate, task.get(Task_.state).in(TaskState.TO_DO, TaskState.ONGOING, TaskState.COMPLETE, TaskState.BLOCKED));
        } else {
            predicate = cb.and(predicate, task.get(Task_.state).in(TaskState.valueOf(taskFilter.getByState())));
        }
    }
    if (taskFilter.getType() != null) {
        predicate = cb.and(predicate, task.get(Task_.type).in(taskFilter.getType()));
    }
    if (taskFilter.getPriority() != null) {
        predicate = cb.and(predicate, task.get(Task_.priority).in(taskFilter.getPriority()));
    }
    if (taskFilter.getAssignee() != null) {
        predicate = cb.and(predicate, task.get(Task_.assignee).get(Account_.id).in(taskFilter.getAssignee().getId()));
    }
    return predicate;
}
Example 30
Project: TeeFun-master  File: QueueDAOImpl.java View source code
@Override
public QueueEntity getByName(final String name) {
    final CriteriaQuery<QueueEntity> criteria = this.builder.createQuery(QueueEntity.class);
    final Root<QueueEntity> queueRoot = criteria.from(QueueEntity.class);
    criteria.select(queueRoot);
    final Predicate namePredicate = this.builder.like(queueRoot.<String>get("name"), name);
    criteria.where(namePredicate);
    try {
        return this.entityManager.createQuery(criteria).getSingleResult();
    } catch (final NoResultException ex) {
        return null;
    }
}
Example 31
Project: zeroth-master  File: NewsRepositoryImpl.java View source code
/**
     * {@inheritDoc}
     * <dl>
     * <dt>事��件</dt>
     * <dd>フィルタ��NULL��る��。</dd>
     * <dt>事後�件</dt>
     * <dd>指定��キーワードを表題�説明�カテゴリ�部分一致�検索�件��る。</dd>
     * </dl>
     */
@Override
protected Predicate expression(final SimpleFilter filter) {
    assert filter != null;
    if (StringUtils.isEmpty(filter.getKeyword())) {
        return super.expression(filter);
    }
    final CriteriaBuilder b = service.builder();
    final Root<News> r = service.root();
    return b.or(b.like(r.get(title), wrapWildcard(filter.getKeyword())), b.like(r.get(description), wrapWildcard(filter.getKeyword())), b.like(r.get(category), wrapWildcard(filter.getKeyword())));
}
Example 32
Project: arquillian-showcase-master  File: GameRepository.java View source code
public List<Game> fetchAllFor(Platform platform) {
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Game> query = criteriaBuilder.createQuery(Game.class);
    Root<Game> fromGames = query.from(Game.class);
    Join<Game, Platform> platformsOfGame = fromGames.join(Game_.supportedPlatforms);
    Predicate givenPlatfromIsAssigned = criteriaBuilder.equal(platformsOfGame.get(Platform_.name), platform.getName());
    CriteriaQuery<Game> allGamesForGivenPlatfrom = query.select(fromGames).where(givenPlatfromIsAssigned);
    return em.createQuery(allGamesForGivenPlatfrom).getResultList();
}
Example 33
Project: bullsfirst-server-java-master  File: BrokerageAccountRepository.java View source code
@SuppressWarnings("unchecked")
public List<Order> findOrders(OrderCriteriaInternal criteria) {
    // TODO: Modify this query to return executions in ascending order of id
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> query = builder.createQuery(Order.class);
    // select * from Order
    Root<Order> _order = query.from(Order.class);
    // Eager fetch executions (because executions are often needed along with orders) 
    _order.fetch(Order_.executions, JoinType.LEFT);
    // Construct a predicate for the where clause using conjunction
    Predicate predicate = builder.conjunction();
    // accountIds
    if (!criteria.getAccountIds().isEmpty()) {
        Path<BrokerageAccount> _account = _order.get(Order_.account);
        Path<Long> _accountId = _account.get(BrokerageAccount_.id);
        CriteriaBuilder.In<Long> inExpr = builder.in(_accountId);
        for (Long accountId : criteria.getAccountIds()) {
            inExpr = inExpr.value(accountId);
        }
        predicate = builder.and(predicate, inExpr);
    }
    // symbol
    if (criteria.getSymbol() != null) {
        predicate = builder.and(predicate, builder.equal(_order.get(Order_.symbol), criteria.getSymbol()));
    }
    // orderId
    if (criteria.getOrderId() != null) {
        predicate = builder.and(predicate, builder.equal(_order.get(Order_.id), criteria.getOrderId()));
    }
    // fromDate
    if (criteria.getFromDate() != null) {
        predicate = builder.and(predicate, builder.greaterThanOrEqualTo(_order.get(Order_.creationTime), criteria.getFromDate().toDateTimeAtStartOfDay()));
    }
    if (criteria.getToDate() != null) {
        predicate = builder.and(predicate, builder.lessThan(_order.get(Order_.creationTime), criteria.getToDate().plusDays(1).toDateTimeAtStartOfDay()));
    }
    if (!criteria.getSides().isEmpty()) {
        CriteriaBuilder.In<OrderSide> inExpr = builder.in(_order.get(Order_.side));
        for (OrderSide side : criteria.getSides()) {
            inExpr = inExpr.value(side);
        }
        predicate = builder.and(predicate, inExpr);
    }
    if (!criteria.getStatuses().isEmpty()) {
        CriteriaBuilder.In<OrderStatus> inExpr = builder.in(_order.get(Order_.status));
        for (OrderStatus status : criteria.getStatuses()) {
            inExpr = inExpr.value(status);
        }
        predicate = builder.and(predicate, inExpr);
    }
    // Assign predicate to where clause
    query.where(predicate);
    // Execute the query
    List<Order> orders = entityManager.createQuery(query).getResultList();
    // Orders with multiple executions will be added to the above list multiple times
    // Filter out duplicates
    Set<Order> distinctOrderSet = new TreeSet<Order>(orders);
    List<Order> distinctOrderList = new ArrayList<Order>(distinctOrderSet);
    return distinctOrderList;
}
Example 34
Project: clinic-softacad-master  File: PredicateTest.java View source code
/**
	 * Check complicated not.
	 */
@Test
public void testComplicatedNotOr() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    CriteriaQuery<Order> orderCriteria = builder.createQuery(Order.class);
    Root<Order> orderRoot = orderCriteria.from(Order.class);
    orderCriteria.select(orderRoot);
    Predicate p1 = builder.equal(orderRoot.get("id"), "order-1");
    Predicate p2 = builder.equal(orderRoot.get("id"), "order-2");
    orderCriteria.where(builder.not(builder.or(p1, p2)));
    List<Order> orders = em.createQuery(orderCriteria).getResultList();
    assertTrue(orders.size() == 1);
    Order order = orders.get(0);
    assertEquals("order-3", order.getId());
    em.getTransaction().commit();
    em.close();
}
Example 35
Project: cmop-master  File: DynamicSpecifications.java View source code
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    if (Collections3.isNotEmpty(filters)) {
        List<Predicate> predicates = Lists.newArrayList();
        for (SearchFilter filter : filters) {
            // nested path translate, 如Taskçš„å??为"user.name"çš„filedName,
            // 转�为Task.user.name属性
            String[] names = StringUtils.split(filter.fieldName, ".");
            Path expression = root.get(names[0]);
            for (int i = 1; i < names.length; i++) {
                expression = expression.get(names[i]);
            }
            switch(filter.operator) {
                case EQ:
                    predicates.add(builder.equal(expression, filter.value));
                    break;
                case LIKE:
                    predicates.add(builder.like(expression, "%" + filter.value + "%"));
                    break;
                case GT:
                    predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                    break;
                case LT:
                    predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                    break;
                case GTE:
                    predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                    break;
                case LTE:
                    predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                    break;
                case NOT:
                    predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                    break;
                case IsNull:
                    predicates.add(builder.isNull(expression));
                    break;
                case NotNull:
                    predicates.add(builder.isNotNull(expression));
                    break;
            }
        }
        if (predicates.size() > 0) {
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    }
    return builder.conjunction();
}
Example 36
Project: curso-javaee-primefaces-master  File: Pedidos.java View source code
private List<Predicate> criarPredicatesParaFiltro(PedidoFilter filtro, Root<Pedido> pedidoRoot, From<?, ?> clienteJoin, From<?, ?> vendedorJoin) {
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    List<Predicate> predicates = new ArrayList<>();
    if (filtro.getNumeroDe() != null) {
        predicates.add(builder.greaterThanOrEqualTo(pedidoRoot.get("id"), filtro.getNumeroDe()));
    }
    if (filtro.getNumeroAte() != null) {
        predicates.add(builder.lessThanOrEqualTo(pedidoRoot.get("id"), filtro.getNumeroAte()));
    }
    if (filtro.getDataCriacaoDe() != null) {
        predicates.add(builder.greaterThanOrEqualTo(pedidoRoot.get("dataCriacao"), filtro.getDataCriacaoDe()));
    }
    if (filtro.getDataCriacaoAte() != null) {
        predicates.add(builder.lessThanOrEqualTo(pedidoRoot.get("dataCriacao"), filtro.getDataCriacaoAte()));
    }
    if (StringUtils.isNotBlank(filtro.getNomeCliente())) {
        predicates.add(builder.like(clienteJoin.get("nome"), "%" + filtro.getNomeCliente() + "%"));
    }
    if (StringUtils.isNotBlank(filtro.getNomeVendedor())) {
        predicates.add(builder.like(vendedorJoin.get("nome"), "%" + filtro.getNomeVendedor() + "%"));
    }
    if (filtro.getStatuses() != null && filtro.getStatuses().length > 0) {
        predicates.add(pedidoRoot.get("status").in(Arrays.asList(filtro.getStatuses())));
    }
    return predicates;
}
Example 37
Project: hibernate-core-ogm-master  File: BasicCriteriaUsageTest.java View source code
@Test
public void testParameterCollection() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    CriteriaQuery<Wall> criteria = em.getCriteriaBuilder().createQuery(Wall.class);
    Root<Wall> from = criteria.from(Wall.class);
    ParameterExpression param = em.getCriteriaBuilder().parameter(String.class);
    SingularAttribute<? super Wall, ?> colorAttribute = em.getMetamodel().entity(Wall.class).getDeclaredSingularAttribute("color");
    assertNotNull("metamodel returned null singular attribute", colorAttribute);
    Predicate predicate = em.getCriteriaBuilder().equal(from.get(colorAttribute), param);
    criteria.where(predicate);
    assertEquals(1, criteria.getParameters().size());
    em.getTransaction().commit();
    em.close();
}
Example 38
Project: hibernate-orm-master  File: SelectCaseTest.java View source code
@Test
public void selectCaseWithValuesShouldWork() {
    EntityManager entityManager = getOrCreateEntityManager();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaBuilder.Case<EnumValue> selectCase = cb.selectCase();
    Predicate somePredicate = cb.equal(cb.literal(1), 1);
    selectCase.when(somePredicate, EnumValue.VALUE_1);
    selectCase.otherwise(EnumValue.VALUE_2);
    CriteriaQuery<Entity> query = cb.createQuery(Entity.class);
    Root<Entity> from = query.from(Entity.class);
    query.select(from).where(cb.equal(from.get("value"), selectCase));
    entityManager.createQuery(query).getResultList();
}
Example 39
Project: hibernate-semantic-query-master  File: NegatedPredicateWrapper.java View source code
private static List<JpaPredicate> negateCompoundExpressions(List<Expression<Boolean>> expressions, CriteriaBuilderImpl criteriaBuilder) {
    if (expressions == null || expressions.isEmpty()) {
        return Collections.emptyList();
    }
    final List<JpaPredicate> negatedExpressions = new ArrayList<>();
    for (Expression<Boolean> expression : expressions) {
        if (Predicate.class.isInstance(expression)) {
            negatedExpressions.add(((JpaPredicate) expression).not());
        } else {
            negatedExpressions.add(criteriaBuilder.not(expression));
        }
    }
    return negatedExpressions;
}
Example 40
Project: javaee7-developer-handbook-master  File: EmployeeCriteriaAdvancedSearchTest.java View source code
public List<Employee> advancedSearch(String firstName, String lastName) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = builder.createQuery(Employee.class);
    Root<Employee> p = c.from(Employee.class);
    List<Predicate> predicates = new ArrayList<>();
    if (firstName != null) {
        predicates.add(builder.like(p.get(Employee_.firstName), firstName));
    }
    if (lastName != null) {
        predicates.add(builder.like(p.get(Employee_.lastName), lastName));
    }
    c.where(predicates.toArray(new Predicate[] {}));
    TypedQuery<Employee> q = em.createQuery(c);
    List<Employee> result = q.getResultList();
    return result;
}
Example 41
Project: JMaNGOS-master  File: SkillLineAbilitySpecs.java View source code
public static Specification<SkillLineAbilityEntity> isRaceMatchToRaceMask(final Races race) {
    return new Specification<SkillLineAbilityEntity>() {

        @Override
        public Predicate toPredicate(final Root<SkillLineAbilityEntity> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
            final Expression<Integer> racemask = cb.literal(race.getMask());
            final Expression<Integer> raceFunction = cb.function("bitwise_and", Integer.class, root.<Integer>get("racemask"), racemask);
            return cb.or(cb.greaterThan(raceFunction, 0), cb.equal(root.get("racemask"), 0));
        }
    };
}
Example 42
Project: jpa-query-by-example-master  File: ByPropertySelectorUtil.java View source code
@SuppressWarnings("unchecked")
public <E> Predicate byPropertySelectors(Root<E> root, CriteriaBuilder builder, SearchParameters sp) {
    List<Predicate> predicates = newArrayList();
    for (PropertySelector<?, ?> selector : sp.getProperties()) {
        if (selector.isBoolean()) {
            byBooleanSelector(root, builder, predicates, sp, (PropertySelector<? super E, Boolean>) selector);
        } else if (selector.isString()) {
            byStringSelector(root, builder, predicates, sp, (PropertySelector<? super E, String>) selector);
        } else {
            byObjectSelector(root, builder, predicates, sp, (PropertySelector<? super E, ?>) selector);
        }
    }
    return jpaUtil.concatPredicate(sp, builder, predicates);
}
Example 43
Project: jubula.core-master  File: PersistenceUtil.java View source code
/**
     * Creates and returns an "in" disjunction (i.e. an "or statement") using 
     * the arguments provided. The returned disjunction is semantically similar 
     * to: "<code>propertyName</code> in <code>expressionList</code>", but 
     * works around the Oracle expression list size limit.
     * </br></br>
     * See: "ORA-01795: maximum number of expressions in a list is 1000"
     * 
     * @param expressionList The expression list for the statement.
     * @param property The property to check with the statement.
     * @param criteriaBuilder The builder to use to construct the disjunction.
     * @return the created disjunction.
     */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Predicate getExpressionDisjunction(Collection expressionList, Path property, CriteriaBuilder criteriaBuilder) {
    List<Predicate> expressionCollections = new ArrayList<Predicate>();
    In currentSet = criteriaBuilder.in(property);
    int count = MAX_DB_VALUE_LIST;
    for (Object expression : expressionList) {
        if (count >= MAX_DB_VALUE_LIST) {
            currentSet = criteriaBuilder.in(property);
            expressionCollections.add(currentSet);
            count = 0;
        }
        currentSet.value(expression);
        count++;
    }
    return criteriaBuilder.or(expressionCollections.toArray(new Predicate[expressionCollections.size()]));
}
Example 44
Project: korok-master  File: SearchQueryBuilder.java View source code
private void prepareQuery(CriteriaQuery<?> q) {
    List<Predicate> andFilters = new ArrayList<>();
    for (String word : keyword.split(" ")) {
        Predicate or = builder.or(buildLikeQueryPart(usr.get(User_.firstName), word), buildLikeQueryPart(usr.get(User_.lastName), word), buildLikeQueryPart(usr.get(User_.nickName), word), buildLikeQueryPart(usr.get(User_.screenName), word), buildEmailQueryPart(word), buildRoomNumberQueryPart(word));
        andFilters.add(or);
    }
    q.where(andFilters.toArray(new Predicate[andFilters.size()]));
    q.distinct(true);
}
Example 45
Project: ODCleanStore-master  File: DbQueryBuilderImpl.java View source code
private <E> void setWhereCriteria(final CriteriaBuilder cb, final CriteriaQuery<E> cq, Root<T> root) {
    // here we use the authentication predicate
    Predicate predicate = null;
    if (authorizator != null) {
        predicate = authorizator.getAuthorizationPredicate(cb, root, entityClass);
    }
    for (Object filter : filters) {
        Predicate filterPredicate = null;
        if (filter instanceof Predicate) {
            // we can use this directly
            filterPredicate = (Predicate) filter;
        } else if (filterTranslators != null) {
            // try to translate it
            for (FilterTranslator translator : filterTranslators) {
                filterPredicate = translator.translate(filter, cb, root);
                if (filterPredicate != null) {
                    break;
                }
            }
        }
        // has been the filter translated ?
        if (filterPredicate == null) {
            throw new UnsupportedOperationException("Filter: " + filter.getClass().getName() + " is not supported.");
        }
        // add to our predicate
        if (predicate == null) {
            predicate = filterPredicate;
        } else {
            predicate = cb.and(predicate, filterPredicate);
        }
    }
    // apply filters
    if (predicate != null) {
        cq.where(predicate);
    } else {
    // nothing to set
    }
}
Example 46
Project: patientview-master  File: ResultHeadingDaoImpl.java View source code
@Override
public ResultHeading get(String headingcode, Specialty specialty) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<ResultHeading> criteria = builder.createQuery(ResultHeading.class);
    Root<ResultHeading> from = criteria.from(ResultHeading.class);
    List<Predicate> wherePredicates = new ArrayList<Predicate>();
    wherePredicates.add(builder.equal(from.get(ResultHeading_.headingcode), headingcode));
    buildWhereClause(criteria, wherePredicates);
    try {
        return getEntityManager().createQuery(criteria).getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}
Example 47
Project: project-student-master  File: TermSpecifications.java View source code
/**
     * Creates a specification used to find terms with the specified testUuid.
     * 
     * @param testRun
     * @return
     */
public static Specification<Term> testRunIs(final TestRun testRun) {
    return new Specification<Term>() {

        @Override
        public Predicate toPredicate(Root<Term> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Predicate p = null;
            if (testRun == null || testRun.getUuid() == null) {
                p = cb.isNull(root.<Term_>get("testRun"));
            } else {
                p = cb.equal(root.<Term_>get("testRun").<TestRun_>get("uuid"), testRun.getUuid());
            }
            return p;
        }
    };
}
Example 48
Project: RMT-master  File: RowCountChecker.java View source code
private Long rowCount(final IEntity entity, final List<String> attributeNames, final EntityManager em) {
    final Class<? extends IEntity> entityClass = entity.getClass();
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<Long> query = cb.createQuery(Long.class);
    final Root<? extends IEntity> root = query.from(entityClass);
    query.select(cb.count(root));
    Predicate condition = null;
    for (final String attributeName : attributeNames) {
        Predicate tmp;
        try {
            tmp = cb.equal(root.<Object>get(attributeName), PropertyUtils.getProperty(entity, attributeName));
        // CHECKSTYLE IGNORE 1 LINES
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
        condition = (condition == null) ? tmp : cb.and(condition, tmp);
    }
    // update on existing element? exclude the element itself
    if (!entity.isNew()) {
        condition = cb.and(condition, cb.notEqual(root.<Long>get("id"), "" + entity.getId()));
    }
    query.where(condition);
    return em.createQuery(query).getSingleResult();
}
Example 49
Project: spring-mvc-qq-weibo-master  File: DynamicSpecifications.java View source code
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    if (Collections3.isNotEmpty(filters)) {
        List<Predicate> predicates = Lists.newArrayList();
        for (SearchFilter filter : filters) {
            // nested path translate, 如Taskçš„å??为"user.name"çš„filedName, 转æ?¢ä¸ºTask.user.name属性
            String[] names = StringUtils.split(filter.fieldName, ".");
            Path expression = root.get(names[0]);
            for (int i = 1; i < names.length; i++) {
                expression = expression.get(names[i]);
            }
            // logic operator
            switch(filter.operator) {
                case EQ:
                    predicates.add(builder.equal(expression, filter.value));
                    break;
                case LIKE:
                    predicates.add(builder.like(expression, "%" + filter.value + "%"));
                    break;
                case GT:
                    predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                    break;
                case LT:
                    predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                    break;
                case GTE:
                    predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                    break;
                case LTE:
                    predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                    break;
            }
        }
        // 将所有�件用 and ��起�
        if (!predicates.isEmpty()) {
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    }
    return builder.conjunction();
}
Example 50
Project: springlab-master  File: ByExampleSpecifications.java View source code
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    EntityType<T> entity = em.getMetamodel().entity(type);
    for (Attribute<T, ?> attr : entity.getDeclaredSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            continue;
        }
        Object attrValue = getValue(example, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(builder.like(root.get(attribute(entity, attr.getName(), String.class)), pattern((String) attrValue)));
                }
            } else {
                predicates.add(builder.equal(root.get(attribute(entity, attr.getName(), attrValue.getClass())), attrValue));
            }
        }
    }
    return predicates.isEmpty() ? builder.conjunction() : builder.and(toArray(predicates, Predicate.class));
}
Example 51
Project: transgalactica-master  File: EmployeDaoImpl.java View source code
// TODO https://jira.spring.io/browse/DATAJPA-51
// TODO https://jira.spring.io/browse/DATACMNS-89
@Override
public List<EmployeSummary> findEmployesByCriteria(EmployeSearchCriteria critereRechercheEmploye) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<EmployeSummary> query = cb.createQuery(EmployeSummary.class);
    Root<AbstractJpaEmployeEntity> from = query.from(AbstractJpaEmployeEntity.class);
    List<Predicate> conditions = new ArrayList<>();
    if (StringUtils.isNotBlank(critereRechercheEmploye.getNomEmploye())) {
        conditions.add(cb.like(cb.upper(from.<String>get("nom")), critereRechercheEmploye.getNomEmploye().toUpperCase()));
    }
    if (critereRechercheEmploye.getDateEmbaucheEmployeDebut() != null) {
        conditions.add(cb.greaterThanOrEqualTo(from.<LocalDate>get("dateEmbauche"), critereRechercheEmploye.getDateEmbaucheEmployeDebut()));
    }
    if (critereRechercheEmploye.getDateEmbaucheEmployeFin() != null) {
        conditions.add(cb.lessThanOrEqualTo(from.<LocalDate>get("dateEmbauche"), critereRechercheEmploye.getDateEmbaucheEmployeFin()));
    }
    if (StringUtils.isNotBlank(critereRechercheEmploye.getImmatriculationVaisseau())) {
        SetJoin<AbstractJpaEmployeEntity, JpaVaisseauEntity> join = from.joinSet("vaisseaux");
        conditions.add(cb.equal(join.get("immatriculation"), critereRechercheEmploye.getImmatriculationVaisseau()));
    }
    query.where(conditions.toArray(new Predicate[conditions.size()]));
    query.orderBy(cb.asc(from.get("nom")));
    query.select(cb.construct(BasicEmployeSummary.class, from.get("matricule"), from.get("nom"), from.get("dateEmbauche"), from.get("type")));
    return em.createQuery(query).getResultList();
}
Example 52
Project: uaicriteria-master  File: RegularQueryPredicateCreator.java View source code
public static <Y extends Comparable<? super Y>> Predicate createGreaterThanPredicate(final boolean toLowerCase, final CriteriaBuilder criteriaBuilder, final Expression<? extends Y> path, final Y value) {
    if (toLowerCase) {
        final String loweredValue = createLoweredValue(value);
        final Expression<String> loweredExpression = createLoweredExpression(criteriaBuilder, path);
        return criteriaBuilder.greaterThan(loweredExpression, loweredValue);
    }
    return criteriaBuilder.greaterThan(path, value);
}
Example 53
Project: aranea-master  File: SectionPageServiceImpl.java View source code
@Override
public List<SectionPage> getSectionPagesByPage(Page page) {
    List<SectionPage> sectionPages = Collections.emptyList();
    CriteriaBuilder cb = genericDao.getCriteriaBuilder();
    CriteriaQuery<SectionPage> cq = cb.createQuery(SectionPage.class);
    Root<SectionPage> root = cq.from(SectionPage.class);
    Predicate whereuser = cb.equal(root.<Page>get("page"), page);
    CriteriaQuery<SectionPage> where = cq.select(root).where(whereuser);
    TypedQuery<SectionPage> query = genericDao.getTypedQuery(where);
    sectionPages = query.getResultList();
    return sectionPages;
}
Example 54
Project: atlas-lb-master  File: NodeMetadataRepository.java View source code
public List<NodeMeta> getNodeMetaDataByAccountIdNodeId(Integer nodeId) {
    List<NodeMeta> list = new ArrayList<NodeMeta>();
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<NodeMeta> criteria = builder.createQuery(NodeMeta.class);
    Root<NodeMeta> nodeMetaRoot = criteria.from(NodeMeta.class);
    Node node = new Node();
    node.setId(nodeId);
    Predicate belongsToNode = builder.equal(nodeMetaRoot.get(NodeMeta_.node), node);
    criteria.select(nodeMetaRoot);
    criteria.where(belongsToNode);
    list = entityManager.createQuery(criteria).getResultList();
    return list;
}
Example 55
Project: BatooJPA-master  File: TestCalendarCriteriaQueryTemporalField.java View source code
@Test
@NoDatasource
public void testCalendar() {
    final Calendar testStartInstant = Calendar.getInstance();
    final CalendarTemporalFieldEntity mainEntity = new CalendarTemporalFieldEntity();
    mainEntity.setCalendar(testStartInstant);
    mainEntity.setDate(testStartInstant.getTime());
    persist(mainEntity);
    this.commit();
    this.close();
    CriteriaBuilder cBuilder = em().getCriteriaBuilder();
    CriteriaQuery<CalendarTemporalFieldEntity> query = cBuilder.createQuery(CalendarTemporalFieldEntity.class);
    Root<CalendarTemporalFieldEntity> root = query.from(CalendarTemporalFieldEntity.class);
    Predicate equal = cBuilder.equal(root.get(CalendarTemporalFieldEntity_.calendar), testStartInstant);
    query.where(equal);
    query.select(root);
    final CalendarTemporalFieldEntity mainEntityReloaded = em().createQuery(query).getSingleResult();
    assertEquals(mainEntity.getId(), mainEntityReloaded.getId());
    assertEquals(testStartInstant.getTime(), mainEntityReloaded.getDate());
    assertEquals(testStartInstant, mainEntityReloaded.getCalendar());
}
Example 56
Project: blaze-persistence-master  File: CompoundPredicate.java View source code
@Override
public AbstractPredicate copyNegated() {
    BooleanOperator operator = getNegatedOperator();
    List<Expression<Boolean>> list = new ArrayList<Expression<Boolean>>(expressions.size());
    for (Expression<Boolean> expr : expressions) {
        if (expr instanceof Predicate) {
            list.add(((Predicate) expr).not());
        }
    }
    return new CompoundPredicate(criteriaBuilder, operator, list);
}
Example 57
Project: dkpro-csniper-master  File: AbstractDao.java View source code
/**
	 * Finds all entities that have the same type as the given example and all fields are equal to
	 * non-null fields in the example.
	 */
protected <TT> CriteriaQuery<TT> queryByExample(TT aExample, String aOrderBy, boolean aAscending) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    @SuppressWarnings("unchecked") CriteriaQuery<TT> query = cb.createQuery((Class<TT>) aExample.getClass());
    @SuppressWarnings("unchecked") Root<TT> root = query.from((Class<TT>) aExample.getClass());
    query.select(root);
    List<Predicate> predicates = new ArrayList<Predicate>();
    BeanWrapper a = PropertyAccessorFactory.forBeanPropertyAccess(aExample);
    // Iterate over all properties
    for (PropertyDescriptor d : a.getPropertyDescriptors()) {
        Object value = a.getPropertyValue(d.getName());
        // property.
        if (value != null && a.isWritableProperty(d.getName())) {
            predicates.add(cb.equal(root.get(d.getName()), value));
        }
    }
    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    }
    if (aOrderBy != null) {
        if (aAscending) {
            query.orderBy(cb.asc(root.get(aOrderBy)));
        } else {
            query.orderBy(cb.desc(root.get(aOrderBy)));
        }
    }
    return query;
}
Example 58
Project: DLect-master  File: DatabaseMergerEJB.java View source code
@Override
public <T> T getObjectFor(Map<SingularAttribute<T, ?>, Object> columnValueMap, Class<T> clz) {
    CriteriaBuilder cb = manager.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(clz);
    Root<T> ud = cq.from(clz);
    List<Predicate> predicates = Lists.newArrayList();
    for (Entry<SingularAttribute<T, ?>, Object> entry : columnValueMap.entrySet()) {
        predicates.add(cb.equal(ud.get(entry.getKey()), entry.getValue()));
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    List<T> r = manager.createQuery(cq).getResultList();
    return r.isEmpty() ? null : r.get(0);
}
Example 59
Project: eGov-master  File: JudgmentTypeService.java View source code
public List<JudgmentType> search(final JudgmentType judgmentType) {
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    final CriteriaQuery<JudgmentType> createQuery = cb.createQuery(JudgmentType.class);
    final Root<JudgmentType> judgmentTypeObj = createQuery.from(JudgmentType.class);
    createQuery.select(judgmentTypeObj);
    final Metamodel m = entityManager.getMetamodel();
    final javax.persistence.metamodel.EntityType<JudgmentType> JudgmentType = m.entity(JudgmentType.class);
    final List<JudgmentType> resultList;
    final List<Predicate> predicates = new ArrayList<Predicate>();
    if (judgmentType.getName() == null && judgmentType.getCode() == null && judgmentType.getActive() == null)
        resultList = findAll();
    else {
        if (judgmentType.getName() != null) {
            final String interimOrderType = "%" + judgmentType.getName().toLowerCase() + "%";
            predicates.add(cb.isNotNull(judgmentTypeObj.get("name")));
            predicates.add(cb.like(cb.lower(judgmentTypeObj.get(JudgmentType.getDeclaredSingularAttribute("name", String.class))), interimOrderType));
        }
        if (judgmentType.getCode() != null) {
            final String code = "%" + judgmentType.getCode().toLowerCase() + "%";
            predicates.add(cb.isNotNull(judgmentTypeObj.get("code")));
            predicates.add(cb.like(cb.lower(judgmentTypeObj.get(JudgmentType.getDeclaredSingularAttribute("code", String.class))), code));
        }
        if (judgmentType.getActive() != null)
            if (judgmentType.getActive())
                predicates.add(cb.equal(judgmentTypeObj.get(JudgmentType.getDeclaredSingularAttribute("active", Boolean.class)), true));
            else
                predicates.add(cb.equal(judgmentTypeObj.get(JudgmentType.getDeclaredSingularAttribute("active", Boolean.class)), false));
        createQuery.where(predicates.toArray(new Predicate[] {}));
        final TypedQuery<JudgmentType> query = entityManager.createQuery(createQuery);
        resultList = query.getResultList();
    }
    return resultList;
}
Example 60
Project: genie-master  File: JpaJobSpecs.java View source code
/**
     * Generate a criteria query predicate for a where clause based on the given parameters.
     *
     * @param root        The root to use
     * @param cb          The criteria builder to use
     * @param id          The job id
     * @param name        The job name
     * @param user        The user who created the job
     * @param statuses    The job statuses
     * @param tags        The tags for the jobs to find
     * @param clusterName The cluster name
     * @param cluster     The cluster the job should have been run on
     * @param commandName The command name
     * @param command     The command the job should have been run with
     * @param minStarted  The time which the job had to start after in order to be return (inclusive)
     * @param maxStarted  The time which the job had to start before in order to be returned (exclusive)
     * @param minFinished The time which the job had to finish after in order to be return (inclusive)
     * @param maxFinished The time which the job had to finish before in order to be returned (exclusive)
     * @return The specification
     */
public static Predicate getFindPredicate(final Root<JobEntity> root, final CriteriaBuilder cb, final String id, final String name, final String user, final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final ClusterEntity cluster, final String commandName, final CommandEntity command, final Date minStarted, final Date maxStarted, final Date minFinished, final Date maxFinished) {
    final List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.isNotBlank(id)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.id), id));
    }
    if (StringUtils.isNotBlank(name)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.name), name));
    }
    if (StringUtils.isNotBlank(user)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.user), user));
    }
    if (statuses != null && !statuses.isEmpty()) {
        final List<Predicate> orPredicates = statuses.stream().map( status -> cb.equal(root.get(JobEntity_.status), status)).collect(Collectors.toList());
        predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
    }
    if (tags != null && !tags.isEmpty()) {
        predicates.add(cb.like(root.get(JobEntity_.tags), JpaSpecificationUtils.getTagLikeString(tags)));
    }
    if (cluster != null) {
        predicates.add(cb.equal(root.get(JobEntity_.cluster), cluster));
    }
    if (StringUtils.isNotBlank(clusterName)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.clusterName), clusterName));
    }
    if (command != null) {
        predicates.add(cb.equal(root.get(JobEntity_.command), command));
    }
    if (StringUtils.isNotBlank(commandName)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.commandName), commandName));
    }
    if (minStarted != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.started), minStarted));
    }
    if (maxStarted != null) {
        predicates.add(cb.lessThan(root.get(JobEntity_.started), maxStarted));
    }
    if (minFinished != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.finished), minFinished));
    }
    if (maxFinished != null) {
        predicates.add(cb.lessThan(root.get(JobEntity_.finished), maxFinished));
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
Example 61
Project: hades-master  File: Specifications.java View source code
/**
     * ANDs the given {@link Specification} to the current one.
     * 
     * @param other
     * @return
     */
public Specifications<T> and(final Specification<T> other) {
    return new Specifications<T>(new Specification<T>() {

        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            return builder.and(spec.toPredicate(root, query, builder), other.toPredicate(root, query, builder));
        }
    });
}
Example 62
Project: idnadrev-master  File: TaskFilterView.java View source code
public void applyFilterOnDS(ViewTasksDS datasource) {
    datasource.setFilter(( root,  query,  builder) -> {
        ArrayList<Predicate> predicates = new ArrayList<>();
        String descriptionText = description.textProperty().getValueSafe().trim();
        if (!descriptionText.isEmpty()) {
            Path<String> desc = root.get(PropertyPath.property(Task.class,  t -> t.getDescription()));
            Predicate like = builder.like(builder.lower(desc), "%" + descriptionText + "%");
            predicates.add(like);
        }
        Path<String> statePath = root.get(PropertyPath.property(Task.class,  t -> t.getState()));
        ArrayList<Predicate> stateOrCombination = new ArrayList<>();
        if (showDefault.isSelected()) {
            stateOrCombination.add(builder.equal(statePath, TaskState.NONE));
        }
        if (showAsap.isSelected()) {
            stateOrCombination.add(builder.equal(statePath, TaskState.ASAP));
        }
        if (showLater.isSelected()) {
            stateOrCombination.add(builder.equal(statePath, TaskState.LATER));
        }
        if (showDelegated.isSelected()) {
            stateOrCombination.add(builder.equal(statePath, TaskState.DELEGATED));
        }
        Predicate or = builder.or(stateOrCombination.toArray(new Predicate[stateOrCombination.size()]));
        predicates.add(or);
        String finishTime = PropertyPath.property(Task.class, ( t) -> t.getFinishTime());
        if (!showFinished.isSelected()) {
            predicates.add(root.get(finishTime).isNull());
        }
        if (parentProjectController.getSelectedValue() != null) {
            Predicate parentNotNull = root.get(PropertyPath.property(Task.class,  t -> t.getParent())).isNotNull();
            Predicate isParent = builder.equal(root.get("id"), parentProjectController.getSelectedValue().getId());
            predicates.add(builder.or(parentNotNull, isParent));
        }
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    });
}
Example 63
Project: jspxcms304-master  File: FriendlinkServiceImpl.java View source code
private Specification<Friendlink> spec(final Integer siteId, Map<String, String[]> params) {
    Collection<SearchFilter> filters = SearchFilter.parse(params).values();
    final Specification<Friendlink> fs = SearchFilter.spec(filters, Friendlink.class);
    Specification<Friendlink> sp = new Specification<Friendlink>() {

        public Predicate toPredicate(Root<Friendlink> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Predicate pred = fs.toPredicate(root, query, cb);
            if (siteId != null) {
                pred = cb.and(pred, cb.equal(root.get("site").get("id"), siteId));
            }
            return pred;
        }
    };
    return sp;
}
Example 64
Project: jsr303-validators-master  File: UniqueKeyValidator.java View source code
@Override
public boolean isValid(final Serializable target, final ConstraintValidatorContext context) {
    if (entityManager == null) {
        // value "NONE" to persistence.xml
        return true;
    }
    final Class<?> entityClass = target.getClass();
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
    final Root<?> root = criteriaQuery.from(entityClass);
    try {
        final Object propertyValue = getPropertyValue(target, constraintAnnotation.property());
        final Predicate uniquePropertyPredicate = criteriaBuilder.equal(root.get(constraintAnnotation.property()), propertyValue);
        final Field idField = getIdField(entityClass);
        final String idProperty = idField.getName();
        final Object idValue = getPropertyValue(target, idProperty);
        if (idValue != null) {
            final Predicate idNotEqualsPredicate = criteriaBuilder.notEqual(root.get(idProperty), idValue);
            criteriaQuery.where(uniquePropertyPredicate, idNotEqualsPredicate);
        } else {
            criteriaQuery.where(uniquePropertyPredicate);
        }
    } catch (final Exception e) {
        throw new RuntimeException("An error occurred when trying to create the jpa predicate for the @UniqueKey '" + constraintAnnotation.property() + "' on bean " + entityClass + ".", e);
    }
    final List<Object> resultSet = entityManager.createQuery(criteriaQuery).getResultList();
    if (!resultSet.isEmpty()) {
        context.buildConstraintViolationWithTemplate(constraintAnnotation.message()).addNode(constraintAnnotation.property()).addConstraintViolation().disableDefaultConstraintViolation();
        return false;
    }
    return true;
}
Example 65
Project: keycloak-master  File: JpaAdminEventQuery.java View source code
@Override
public List<AdminEvent> getResultList() {
    if (!predicates.isEmpty()) {
        cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    }
    cq.orderBy(cb.desc(root.get("time")));
    TypedQuery<AdminEventEntity> query = em.createQuery(cq);
    if (firstResult != null) {
        query.setFirstResult(firstResult);
    }
    if (maxResults != null) {
        query.setMaxResults(maxResults);
    }
    List<AdminEvent> events = new LinkedList<AdminEvent>();
    for (AdminEventEntity e : query.getResultList()) {
        events.add(JpaEventStoreProvider.convertAdminEvent(e));
    }
    return events;
}
Example 66
Project: Netuno-master  File: PortoServiceImpl.java View source code
/**
	 * Faz uma consulta ao banco pelos portos com os atributos iguais aos setados no parâmetro porto.
	 * @param porto uma instância de {@link Porto} com os atributos da consulta.
	 */
@Override
public List<Porto> filtrar(Porto porto) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Porto> consulta = cb.createQuery(Porto.class);
    Root<Porto> portoRoot = consulta.from(Porto.class);
    ArrayList<Predicate> predicados = new ArrayList<Predicate>();
    if (porto != null) {
        //Cada atributo setado em porto é um filtro e portanto é colocado numa lista de predicados
        if (porto.getLocalizacao() != null && !porto.getLocalizacao().equals("")) {
            Expression<String> localizacao = portoRoot.get("localizacao");
            predicados.add(cb.like(cb.lower(localizacao), porto.getLocalizacao().toLowerCase() + "%"));
        }
        if (porto.getNome() != null && !porto.getNome().equals("")) {
            Expression<String> nome = portoRoot.get("nome");
            predicados.add(cb.like(cb.lower(nome), porto.getNome().toLowerCase() + "%"));
        }
    }
    //Executa a consulta com Porto como entidade raiz e satisfazendo as condições dos predicados
    consulta.select(portoRoot).where(predicados.toArray(new Predicate[] {}));
    consulta.orderBy(cb.asc((portoRoot.get("localizacao"))));
    return this.em.createQuery(consulta).getResultList();
}
Example 67
Project: org.ops4j.pax.exam2-master  File: MoviesImpl.java View source code
private List<Movie> findByStringField(String fieldname, String param) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Movie> query = builder.createQuery(Movie.class);
    Root<Movie> root = query.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
    Path<String> path = root.get(type.getDeclaredSingularAttribute(fieldname, String.class));
    Predicate condition = builder.like(path, "%" + param + "%");
    query.where(condition);
    return entityManager.createQuery(query).getResultList();
}
Example 68
Project: permutas-sep-master  File: ResourceServiceImpl.java View source code
@Override
@Transactional
public List<Sentence> search(String sentence) {
    CriteriaQuery<Sentence> c = em.getCriteriaBuilder().createQuery(Sentence.class);
    Root<Sentence> roleRoot = c.from(Sentence.class);
    c.select(roleRoot);
    Expression<String> exp = roleRoot.get("sentence");
    Predicate r = em.getCriteriaBuilder().like(exp, "%" + sentence + "%");
    c.where(r);
    return em.createQuery(c).getResultList();
}
Example 69
Project: query-master  File: JoinBuilder.java View source code
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path) {
    Join join = null;
    if (singular != null) {
        join = joinSingular((From) path);
    } else if (list != null) {
        join = joinList((From) path);
    } else if (collection != null) {
        join = joinCollection((From) path);
    } else if (set != null) {
        join = joinSet((From) path);
    } else {
        join = joinMap((From) path);
    }
    return criteria.predicates(builder, join);
}
Example 70
Project: resource-server-master  File: ExtensionDao.java View source code
/**
     * Retrieves the extension with the given URN from the database
     *
     * @param urn             the URN of the extension to look up
     * @param caseInsensitive should the case of the URN be ignored
     * @return the extension entity
     */
public ExtensionEntity getExtensionByUrn(String urn, boolean caseInsensitive) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<ExtensionEntity> cq = cb.createQuery(ExtensionEntity.class);
    Root<ExtensionEntity> extension = cq.from(ExtensionEntity.class);
    Predicate predicate;
    if (caseInsensitive) {
        predicate = cb.equal(cb.lower(extension.get(ExtensionEntity_.urn)), urn.toLowerCase(Locale.ENGLISH));
    } else {
        predicate = cb.equal(extension.get(ExtensionEntity_.urn), urn);
    }
    cq.select(extension).where(predicate);
    TypedQuery<ExtensionEntity> query = em.createQuery(cq);
    ExtensionEntity singleExtension;
    try {
        singleExtension = query.getSingleResult();
    } catch (NoResultException e) {
        String message = String.format("Extension with urn '%s' not found", urn);
        LOGGER.warn(message);
        throw new NoSuchElementException(message);
    }
    return singleExtension;
}
Example 71
Project: sigmah-master  File: ContactModelHibernateDAO.java View source code
@Override
public List<ContactModel> findByOrganizationAndTypeAndIds(Integer organizationId, ContactModelType type, Set<Integer> contactModelIds, boolean onlyAvailable) {
    // Too much nullable parameters, let's use criteria query builder to ease the query creation
    // and to avoid using dangerous string concatenation
    CriteriaBuilder criteriaBuilder = em().getCriteriaBuilder();
    CriteriaQuery<ContactModel> criteriaQuery = criteriaBuilder.createQuery(ContactModel.class);
    Root<ContactModel> contactModelRoot = criteriaQuery.from(ContactModel.class);
    Join<Object, Object> organizationJoin = contactModelRoot.join("organization", JoinType.INNER);
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(criteriaBuilder.equal(organizationJoin.get("id"), organizationId));
    if (type != null) {
        predicates.add(criteriaBuilder.equal(contactModelRoot.get("type"), type));
    }
    if (contactModelIds != null && !contactModelIds.isEmpty()) {
        predicates.add(contactModelRoot.get("id").in(contactModelIds));
    }
    if (onlyAvailable) {
        predicates.add(contactModelRoot.get("status").in(Arrays.asList(ProjectModelStatus.READY, ProjectModelStatus.USED)));
    }
    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
    criteriaQuery.select(contactModelRoot);
    criteriaQuery.orderBy(criteriaBuilder.asc(contactModelRoot.get("name")));
    return em().createQuery(criteriaQuery).getResultList();
}
Example 72
Project: spring-data-jpa-master  File: ParentRepositoryIntegrationTests.java View source code
// DATAJPA-287
@Test
public void testWithoutJoin() throws Exception {
    Page<Parent> page = repository.findAll(new Specification<Parent>() {

        public Predicate toPredicate(Root<Parent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<Set<Child>> childrenPath = root.get("children");
            query.distinct(true);
            return cb.isNotEmpty(childrenPath);
        }
    }, PageRequest.of(0, 5, Sort.by(Sort.Direction.ASC, "id")));
    List<Parent> content = page.getContent();
    assertThat(content.size(), is(3));
    assertThat(page.getSize(), is(5));
    assertThat(page.getNumber(), is(0));
    assertThat(page.getTotalElements(), is(3L));
    assertThat(page.getTotalPages(), is(1));
}
Example 73
Project: swag4911-master  File: AbstractDataAccessObject.java View source code
private <T> List<T> findByExample(T example, Class<T> clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(clazz);
    Root<T> r = cq.from(clazz);
    Predicate p = cb.conjunction();
    Metamodel mm = em.getMetamodel();
    EntityType<T> et = mm.entity(clazz);
    Set<Attribute<? super T, ?>> attrs = et.getAttributes();
    for (Attribute<? super T, ?> a : attrs) {
        String name = a.getName();
        String javaName = a.getJavaMember().getName();
        String getter = "get" + javaName.substring(0, 1).toUpperCase() + javaName.substring(1);
        Method m = clazz.getMethod(getter, (Class<?>[]) null);
        Object value = m.invoke(example, (Object[]) null);
        if (value != null) {
            if (!a.isCollection())
                p = cb.and(p, cb.equal(r.get(name), value));
            if (a.isAssociation())
                r.fetch(name);
        }
    }
    cq.select(r).where(p);
    TypedQuery<T> query = em.createQuery(cq);
    return query.getResultList();
}
Example 74
Project: tomee-master  File: MoviesBean.java View source code
public int count(String field, String searchTerm) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = qb.createQuery(Long.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
    Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
    Predicate condition = qb.like(path, "%" + searchTerm + "%");
    cq.select(qb.count(root));
    cq.where(condition);
    return entityManager.createQuery(cq).getSingleResult().intValue();
}
Example 75
Project: trade-manager-master  File: ContractHome.java View source code
/**
	 * Method findByUniqueKey.
	 * 
	 * @param SECType
	 *            String
	 * @param symbol
	 *            String
	 * @param exchange
	 *            String
	 * @param currency
	 *            String
	 * @param expiryDate
	 *            ZonedDateTime
	 * @return Contract
	 */
public Contract findByUniqueKey(String SECType, String symbol, String exchange, String currency, ZonedDateTime expiryDate) {
    try {
        EntityManager entityManager = EntityManagerHelper.getEntityManager();
        entityManager.getTransaction().begin();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Contract> query = builder.createQuery(Contract.class);
        Root<Contract> from = query.from(Contract.class);
        query.select(from);
        List<Predicate> predicates = new ArrayList<Predicate>();
        if (null != SECType) {
            Predicate predicate = builder.equal(from.get("secType"), SECType);
            predicates.add(predicate);
        }
        if (null != symbol) {
            Predicate predicate = builder.equal(from.get("symbol"), symbol);
            predicates.add(predicate);
        }
        if (null != exchange) {
            Predicate predicate = builder.equal(from.get("exchange"), exchange);
            predicates.add(predicate);
        }
        if (null != currency) {
            Predicate predicate = builder.equal(from.get("currency"), currency);
            predicates.add(predicate);
        }
        if (null != expiryDate) {
            Integer yearExpiry = expiryDate.getYear();
            Expression<Integer> year = builder.function("year", Integer.class, from.get("expiry"));
            Predicate predicateYear = builder.equal(year, yearExpiry);
            predicates.add(predicateYear);
            Integer monthExpiry = expiryDate.getMonthValue();
            Expression<Integer> month = builder.function("month", Integer.class, from.get("expiry"));
            Predicate predicateMonth = builder.equal(month, monthExpiry);
            predicates.add(predicateMonth);
        }
        query.where(predicates.toArray(new Predicate[] {}));
        TypedQuery<Contract> typedQuery = entityManager.createQuery(query);
        List<Contract> items = typedQuery.getResultList();
        entityManager.getTransaction().commit();
        if (items.size() > 0) {
            return items.get(0);
        }
        return null;
    } catch (Exception re) {
        EntityManagerHelper.rollback();
        throw re;
    } finally {
        EntityManagerHelper.close();
    }
}
Example 76
Project: vipera-master  File: DoctorDaoImpl.java View source code
/**
     * {@link DoctorBrowseFilter} nesnesini {@link CriteriaQuery} nesnesine
     * dönüştürür
     * 
     * @param filter
     *            filtre
     * @return
     */
private CriteriaQuery<Doctor> creataCriteriaQueryFromFilter(final DoctorBrowseFilter filter) {
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<Doctor> cq = cb.createQuery(Doctor.class);
    final Root<Doctor> root = cq.from(Doctor.class);
    final Map<String, Object> filters = filter.getFilters();
    final List<Predicate> predicates = new ArrayList<Predicate>();
    for (final String attr : filters.keySet()) {
        final Object obj = filters.get(attr);
        if (obj != null && !obj.toString().isEmpty()) {
            final String pattern = '%' + obj.toString() + '%';
            predicates.add(cb.like(root.<String>get(attr).as(String.class), pattern));
        }
    }
    cq.select(root).where(predicates.toArray(new Predicate[0]));
    return cq;
}
Example 77
Project: Weaves-master  File: JPAPagedGridDataSource.java View source code
@Override
public List<T> fetchResult(int startIndex, int endIndexPlusOne, List<SortConstraint> sortConstraints) {
    // We just assume that the property names in the SortContraint match the Hibernate
    // properties.
    cb = em.getCriteriaBuilder();
    final CriteriaQuery<T> cq = cb.createQuery(getRowType());
    // the FROM clause
    root = cq.from(getRowType());
    predicates = new ArrayList<Predicate>();
    //Constructing list of parameters
    // use the predicates, cb and root fields to fill up the filters
    applyFiltering();
    final List<String> orderedFields = new ArrayList<String>();
    for (final SortConstraint constraint : sortConstraints) {
        final String propertyName = constraint.getPropertyModel().getPropertyName();
        if (!orderedFields.contains(propertyName)) {
            orderedFields.add(propertyName);
            switch(constraint.getColumnSort()) {
                case ASCENDING:
                    cq.orderBy(cb.asc(root.get(propertyName)));
                    break;
                case DESCENDING:
                    cq.orderBy(cb.desc(root.get(propertyName)));
                    break;
                default:
            }
        }
    }
    cq.select(root).where(predicates.toArray(new Predicate[] {}));
    final TypedQuery<T> q = em.createQuery(cq);
    q.setFirstResult(startIndex);
    q.setMaxResults(endIndexPlusOne - startIndex + 1);
    return q.getResultList();
}
Example 78
Project: activejpa-master  File: FilterTest.java View source code
@Test
public void shouldConstructCriteriaQuery() {
    Filter filter = new Filter(mock(Condition.class), mock(Condition.class));
    CriteriaBuilder builder = mock(CriteriaBuilder.class);
    Root root = mock(Root.class);
    Predicate p1 = mock(Predicate.class);
    Predicate p2 = mock(Predicate.class);
    when(filter.getConditions().get(0).constructQuery(builder, root)).thenReturn(p1);
    when(filter.getConditions().get(1).constructQuery(builder, root)).thenReturn(p2);
    CriteriaQuery query = mock(CriteriaQuery.class);
    filter.constructQuery(builder, query, root);
    verify(query).where(p1, p2);
}
Example 79
Project: catwatch-master  File: ContributorRepositoryImpl.java View source code
@Override
public List<Contributor> findAllTimeTopContributors(Long organizationId, Date snapshotDate, String namePrefix, Integer offset, Integer limit) {
    checkNotNull(snapshotDate, "snapshot date must not be null but was");
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contributor> cq = cb.createQuery(Contributor.class);
    // define "from" and joins
    Root<Contributor> contributor = cq.from(Contributor.class);
    Path<ContributorKey> key = contributor.get("key");
    // define constraints
    List<Predicate> andPredicates = new ArrayList<>();
    {
        if (organizationId != null) {
            andPredicates.add(cb.equal(key.get("organizationId"), organizationId));
        }
        andPredicates.add(cb.equal(key.<Date>get("snapshotDate"), snapshotDate));
        if (namePrefix != null) {
            andPredicates.add(cb.like(contributor.get("name"), namePrefix.replace("%", "[%]") + "%"));
        }
    }
    return em.createQuery(//
    cq.select(//
    contributor).where(andPredicates.toArray(new Predicate[andPredicates//
    .size()])).orderBy(cb.desc(contributor.get("organizationalCommitsCount")))).setFirstResult(//
    offset == null ? //
    0 : //
    offset).setMaxResults(limit == null ? 10000000 : limit).getResultList();
}
Example 80
Project: deltaspike-master  File: JoinBuilder.java View source code
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path) {
    Join join = null;
    if (singular != null) {
        join = joinSingular((From) path);
    } else if (list != null) {
        join = joinList((From) path);
    } else if (collection != null) {
        join = joinCollection((From) path);
    } else if (set != null) {
        join = joinSet((From) path);
    } else {
        join = joinMap((From) path);
    }
    return criteria.predicates(builder, join);
}
Example 81
Project: devicehive-java-server-master  File: NetworkDaoRdbmsImpl.java View source code
@Override
public List<NetworkVO> list(String name, String namePattern, String sortField, boolean sortOrderAsc, Integer take, Integer skip, Optional<HivePrincipal> principal) {
    CriteriaBuilder cb = criteriaBuilder();
    CriteriaQuery<Network> criteria = cb.createQuery(Network.class);
    Root<Network> from = criteria.from(Network.class);
    Predicate[] nameAndPrincipalPredicates = CriteriaHelper.networkListPredicates(cb, from, ofNullable(name), ofNullable(namePattern), principal);
    criteria.where(nameAndPrincipalPredicates);
    CriteriaHelper.order(cb, criteria, from, ofNullable(sortField), sortOrderAsc);
    TypedQuery<Network> query = createQuery(criteria);
    cacheQuery(query, of(CacheConfig.refresh()));
    ofNullable(take).ifPresent(query::setMaxResults);
    ofNullable(skip).ifPresent(query::setFirstResult);
    List<Network> result = query.getResultList();
    Stream<NetworkVO> objectStream = result.stream().map(Network::convertNetwork);
    return objectStream.collect(Collectors.toList());
}
Example 82
Project: document-management-master  File: JPADocumentsCatalog.java View source code
private void applyCriteria(DocumentCriteria documentCriteria, CriteriaBuilder builder, CriteriaQuery query, Root<Document> root) {
    Collection<Predicate> predicates = new HashSet<>();
    applyStatus(documentCriteria, builder, root, predicates);
    applyCreatedBy(documentCriteria, builder, root, predicates);
    applyVerifiedBy(documentCriteria, builder, root, predicates);
    applyCreatedFrom(documentCriteria, builder, root, predicates);
    applyCreatedUntil(documentCriteria, builder, root, predicates);
    applyVerifiedFrom(documentCriteria, builder, root, predicates);
    applyVerifiedUntil(documentCriteria, builder, root, predicates);
    applyQuery(documentCriteria, builder, root, predicates);
    applyNotDeleted(documentCriteria, builder, root, predicates);
    query.where(predicates.toArray(new Predicate[] {}));
}
Example 83
Project: Foodoo-backend-master  File: OrderDao.java View source code
public List<Order> getOrdersByStatuses(List<OrderStatus> statuses) {
    if (statuses == null)
        throw new NullPointerException("statuses");
    if (statuses.isEmpty())
        return Collections.emptyList();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Order> query = cb.createQuery(Order.class);
    Root<Order> root = query.from(Order.class);
    query.select(root);
    List<Predicate> statusPredicates = statuses.stream().map(( status) -> cb.equal(root.get(Order_.status), status)).collect(Collectors.toList());
    query.where(cb.or(statusPredicates.toArray(new Predicate[0])));
    TypedQuery<Order> typedQuery = em.createQuery(query);
    return typedQuery.getResultList();
}
Example 84
Project: IBE-Secure-Message-master  File: IdentityDescriptionBeanImpl.java View source code
/*
     * (non-Javadoc)
     * @see hamaster.gradesign.idmgmt.IdentityDescriptionBean#get(java.lang.String)
     */
@Override
public IdentityDescriptionEntity get(String owner) {
    EntityManager manager = factory.createEntityManager();
    CriteriaBuilder cb = manager.getCriteriaBuilder();
    CriteriaQuery<IdentityDescriptionEntity> query = cb.createQuery(IdentityDescriptionEntity.class);
    Root<IdentityDescriptionEntity> root = query.from(IdentityDescriptionEntity.class);
    Predicate condition = cb.equal(root.get("idOwner"), owner);
    query.where(condition);
    return manager.createQuery(query).getSingleResult();
}
Example 85
Project: ilves-master  File: CompanyDao.java View source code
/**
     * Gets company.
     * @param entityManager the entity manager
     * @param host the company host name
     * @return company or null
     */
public static Company getCompany(final EntityManager entityManager, final String host) {
    final CriteriaBuilder queryBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Company> criteriaQuery = queryBuilder.createQuery(Company.class);
    final Root<Company> companyRoot = criteriaQuery.from(Company.class);
    final Predicate condition = queryBuilder.equal(companyRoot.get("host"), host);
    criteriaQuery.where(condition);
    final TypedQuery<Company> typedQuery = entityManager.createQuery(criteriaQuery);
    final List<Company> companies = typedQuery.getResultList();
    if (companies.size() > 0) {
        return companies.get(0);
    } else {
        return null;
    }
}
Example 86
Project: inspectIT-master  File: TimerDataChartingCmrProcessor.java View source code
/**
	 * Find {@link HttpInfo} to attach to {@link HttpTimerData} when saving.
	 *
	 * @param httpTimerData
	 *            {@link HttpTimerData} to find info for.
	 * @param entityManager
	 *            EntityManager
	 * @return {@link HttpInfo}.
	 */
private HttpInfo getHttpInfo(HttpTimerData httpTimerData, EntityManager entityManager) {
    HttpInfo httpInfo = httpTimerData.getHttpInfo();
    // NOPMD
    String uri = httpInfo.isUriDefined() ? httpInfo.getUri() : null;
    // NOPMD
    String tag = httpInfo.hasInspectItTaggingHeader() ? httpInfo.getInspectItTaggingHeaderValue() : null;
    String requestMethod = httpInfo.getRequestMethod();
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<HttpInfo> criteria = builder.createQuery(HttpInfo.class);
    Root<? extends HttpInfo> root = criteria.from(HttpInfo.class);
    Predicate uriPredicate;
    Predicate tagPredicate;
    Predicate requestMethodPredicate = builder.equal(root.get("requestMethod"), requestMethod);
    if (null != uri) {
        uriPredicate = builder.equal(root.get("uri"), uri);
    } else {
        uriPredicate = builder.isNull(root.get("uri"));
    }
    if (null != tag) {
        tagPredicate = builder.equal(root.get("inspectItTaggingHeaderValue"), tag);
    } else {
        tagPredicate = builder.isNull(root.get("inspectItTaggingHeaderValue"));
    }
    criteria.where(uriPredicate, tagPredicate, requestMethodPredicate);
    List<?> httpInfoList = entityManager.createQuery(criteria).getResultList();
    if (CollectionUtils.isNotEmpty(httpInfoList)) {
        return (HttpInfo) httpInfoList.get(0);
    } else {
        return new HttpInfo(uri, requestMethod, tag);
    }
}
Example 87
Project: kraken-master  File: LogQueryCondition.java View source code
@Override
public Predicate getPredicate(CriteriaBuilder cb, Root<?> root) {
    Predicate p = cb.equal(root.get("orgId"), orgId);
    if (agentId != null)
        p = cb.and(p, cb.equal(root.join("agent").get("id"), agentId));
    if (from != null)
        p = cb.and(p, cb.greaterThanOrEqualTo(root.<Date>get("date"), from));
    if (to != null)
        p = cb.and(p, cb.lessThanOrEqualTo(root.<Date>get("date"), to));
    if (type != null)
        p = cb.and(p, cb.equal(root.get("type"), type.getCode()));
    if (ipFrom != null) {
        Predicate p1 = cb.between(root.<Long>get("ip1long"), ipFrom, ipTo);
        Predicate p2 = cb.between(root.<Long>get("ip2long"), ipFrom, ipTo);
        p = cb.and(p, cb.or(p1, p2));
    }
    if (mac != null) {
        String m = "%" + mac.toUpperCase() + "%";
        Predicate p1 = cb.like(root.<String>get("mac1"), m);
        Predicate p2 = cb.like(root.<String>get("mac2"), m);
        p = cb.and(p, cb.or(p1, p2));
    }
    return p;
}
Example 88
Project: mycellar-master  File: JpaContactRepository.java View source code
@Override
public long countLastContacts(SearchParameters<Contact> searchParameters) {
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
    Root<Contact> root = query.from(Contact.class);
    Subquery<Contact> subquery = query.subquery(Contact.class);
    Root<Contact> subroot = subquery.from(Contact.class);
    subquery.select(subroot).where(criteriaBuilder.equal(root.get("producer"), subroot.get("producer")), criteriaBuilder.greaterThan(subroot.<LocalDate>get("current"), root.<LocalDate>get("current")));
    Predicate predicate = getPredicate(query, root, criteriaBuilder, searchParameters);
    if (predicate == null) {
        predicate = criteriaBuilder.not(criteriaBuilder.exists(subquery));
    } else {
        predicate = criteriaBuilder.and(predicate, criteriaBuilder.not(criteriaBuilder.exists(subquery)));
    }
    return getEntityManager().createQuery(query.select(criteriaBuilder.count(root)).where(predicate)).getSingleResult();
}
Example 89
Project: olog-service-master  File: TagManagerTest.java View source code
/**
     * Returns the list of tags in the database.
     *
     * @return Tags
     * @throws edu.msu.nscl.olog.OlogException wrapping an SQLException
     */
public static Tags findAll() throws OlogException {
    em = JPAUtilTest.getEntityManagerFactory().createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Tag> cq = cb.createQuery(Tag.class);
    Root<Tag> from = cq.from(Tag.class);
    CriteriaQuery<Tag> select = cq.select(from);
    Predicate statusPredicate = cb.equal(from.get("state"), State.Active);
    select.where(statusPredicate);
    select.orderBy(cb.asc(from.get("name")));
    TypedQuery<Tag> typedQuery = em.createQuery(select);
    JPAUtilTest.startTransaction(em);
    try {
        Tags result = new Tags();
        List<Tag> rs = typedQuery.getResultList();
        if (rs != null) {
            Iterator<Tag> iterator = rs.iterator();
            while (iterator.hasNext()) {
                result.addTag(iterator.next());
            }
        }
        return result;
    } catch (Exception e) {
        throw new OlogException(Response.Status.INTERNAL_SERVER_ERROR, "JPA exception: " + e);
    } finally {
        JPAUtilTest.finishTransacton(em);
    }
}
Example 90
Project: openengsb-master  File: ConnectorJPAPersistenceBackendService.java View source code
private List<ConnectorConfigurationJPAEntity> searchForMetadata(Map<String, String> metaData) throws PersistenceException {
    synchronized (entityManager) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<ConnectorConfigurationJPAEntity> query = cb.createQuery(ConnectorConfigurationJPAEntity.class);
        Root<ConnectorConfigurationJPAEntity> from = query.from(ConnectorConfigurationJPAEntity.class);
        List<Predicate> predicates = new ArrayList<Predicate>();
        if (metaData.get(Constants.CONNECTOR_PERSISTENT_ID) != null) {
            predicates.add(cb.equal(from.get("instanceId"), metaData.get(Constants.CONNECTOR_PERSISTENT_ID)));
        }
        query.select(from);
        query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
        try {
            return entityManager.createQuery(query).getResultList();
        } catch (Exception ex) {
            throw new PersistenceException(ex);
        }
    }
}
Example 91
Project: openjpa-master  File: TestCQL.java View source code
public void testLogicalPrecedence() {
    OpenJPACriteriaQuery<Person> q = cb.createQuery(Person.class);
    Root<Person> p = q.from(Person.class);
    q.select(p);
    Predicate a = cb.equal(p.get(Person_.name), "A");
    Predicate b = cb.equal(p.get(Person_.name), "B");
    Predicate c = cb.equal(p.get(Person_.name), "C");
    Predicate d = cb.equal(p.get(Person_.name), "D");
    // (a OR b) AND (c or D)
    q.where(cb.or(a, b), cb.or(c, d));
    String jpql = "";
    // The strings are compared for exact match so be careful about spaces and such... 
    jpql = "SELECT p FROM Person p WHERE ((p.name = 'A' OR p.name = 'B') AND (p.name = 'C' OR p.name = 'D'))";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
    // (a OR b or C) AND D
    q.where(cb.or(a, b, c), d);
    jpql = "SELECT p FROM Person p WHERE ((p.name = 'A' OR p.name = 'B' OR p.name = 'C') AND p.name = 'D')";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
    // a AND (b OR c) AND d 
    q.where(a, cb.or(b, c), d);
    jpql = "SELECT p FROM Person p WHERE (p.name = 'A' AND (p.name = 'B' OR p.name = 'C') AND p.name = 'D')";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
    // a OR (b AND (c OR d)) 
    q.where(cb.or(a, cb.and(b, cb.or(c, d))));
    jpql = "SELECT p FROM Person p WHERE (p.name = 'A' OR (p.name = 'B' AND (p.name = 'C' OR p.name = 'D')))";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
    // NOT (a OR b) 
    q.where(cb.or(a, b).not());
    jpql = "SELECT p FROM Person p WHERE NOT (p.name = 'A' OR p.name = 'B')";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
    // NOT a 
    q.where(cb.and(a).not());
    jpql = "SELECT p FROM Person p WHERE NOT p.name = 'A'";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
    // NOT a OR NOT b
    q.where(cb.or(cb.not(a), cb.not(b)));
    jpql = "SELECT p FROM Person p WHERE (p.name <> 'A' OR p.name <> 'B')";
    assertEquivalence(q, jpql);
    assertEquals(jpql, q.toCQL());
}
Example 92
Project: organigramme-master  File: PersistentManager.java View source code
@SuppressWarnings("unchecked")
private TypedQuery<T> constructTypedQueryByPropertyOrderBy(Class<? extends T> classe, String property, Object value, String orderByProperty) {
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<T> c = (CriteriaQuery<T>) qb.createQuery(classe);
    Root<T> p = (Root<T>) c.from(classe);
    Predicate condition = qb.equal(p.get(property), value);
    c.where(condition);
    if (orderByProperty != null) {
        c.orderBy(qb.asc(p.get(orderByProperty)));
    }
    TypedQuery<T> q = em.createQuery(c);
    return q;
}
Example 93
Project: pyramus-master  File: SubjectDAO.java View source code
public List<Subject> listByEducationType(EducationType educationType) {
    EntityManager entityManager = getEntityManager();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Subject> criteria = criteriaBuilder.createQuery(Subject.class);
    Root<Subject> root = criteria.from(Subject.class);
    criteria.select(root);
    Predicate educationTypePredicate;
    if (educationType != null)
        educationTypePredicate = criteriaBuilder.equal(root.get(Subject_.educationType), educationType);
    else
        educationTypePredicate = criteriaBuilder.isNull(root.get(Subject_.educationType));
    criteria.where(criteriaBuilder.and(criteriaBuilder.equal(root.get(Subject_.archived), Boolean.FALSE), educationTypePredicate));
    return entityManager.createQuery(criteria).getResultList();
}
Example 94
Project: quickstart-master  File: MemberDaoImpl.java View source code
public List<Member> findByNameAndEmail(String name, String email) {
    log.fine("findByNameAndEmail name = " + name + ", email = " + email);
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Member> criteria = cb.createQuery(Member.class);
    EntityType<Member> type = em.getMetamodel().entity(Member.class);
    Root<Member> member = criteria.from(Member.class);
    List<Predicate> predicatesList = new ArrayList<>();
    // If the name exist create the Predicate for a LIKE comparison of the name.
    if (name != null && !name.isEmpty()) {
        Predicate isLikeName = cb.like(cb.lower(member.get(type.getDeclaredSingularAttribute("name", String.class))), "%" + name.toLowerCase() + "%");
        predicatesList.add(isLikeName);
    }
    // If the email exist create the Predicate for a LIKE comparison of the email.
    if (email != null && !email.isEmpty()) {
        Predicate isLikeEmail = cb.like(cb.lower(member.get(type.getDeclaredSingularAttribute("email", String.class))), "%" + email.toLowerCase() + "%");
        predicatesList.add(isLikeEmail);
    }
    // Add the Predicates to the criteria query. A predicate is utilized for filtering the result only when it is provided.
    criteria.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
    return em.createQuery(criteria).getResultList();
}
Example 95
Project: shop-repo-master  File: BestellungServiceImpl.java View source code
@Override
@Size(min = 1, message = "{bestellung.notFound.ids}")
public List<Bestellung> findBestellungenByIds(List<Long> ids, FetchType fetch) {
    if (ids == null || ids.isEmpty()) {
        return Collections.emptyList();
    }
    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final CriteriaQuery<Bestellung> criteriaQuery = builder.createQuery(Bestellung.class);
    final Root<Bestellung> b = criteriaQuery.from(Bestellung.class);
    final Path<Long> idPath = b.get("id");
    final List<Predicate> predList = new ArrayList<>();
    for (Long id : ids) {
        final Predicate equal = builder.equal(idPath, id);
        predList.add(equal);
    }
    final Predicate[] predArray = new Predicate[predList.size()];
    final Predicate pred = builder.or(predList.toArray(predArray));
    criteriaQuery.where(pred).distinct(true);
    final TypedQuery<Bestellung> query = em.createQuery(criteriaQuery);
    if (FetchType.MIT_LIEFERUNGEN.equals(fetch)) {
        final EntityGraph<?> entityGraph = em.getEntityGraph(Bestellung.GRAPH_LIEFERUNGEN);
        query.setHint(LOADGRAPH, entityGraph);
    }
    return query.getResultList();
}
Example 96
Project: tapestry-model-master  File: SearchableJpaGridDataSource.java View source code
protected void applyAdditionalConstraints(final CriteriaQuery<?> criteria, final Root<?> root, final CriteriaBuilder builder) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (searchTerms != null && searchTerms.length > 0) {
        for (TynamoPropertyDescriptor searchableProperty : searchablePropertyDescriptors) {
            for (String searchTerm : searchTerms) predicates.add(builder.like(root.<String>get(searchableProperty.getName()), searchTerm));
        }
        Predicate predicate = builder.or(predicates.toArray(new Predicate[predicates.size()]));
        criteria.where(applyAdditionalConstraints(builder, root, predicate));
    } else {
        Predicate predicate = applyAdditionalConstraints(builder, root, null);
        if (predicate != null)
            criteria.where(predicate);
    }
}
Example 97
Project: wte4j-master  File: WordTemplateQuery.java View source code
private Predicate buildPropertyRestriction(MapJoin<PersistentTemplate, String, String> propertiesMap, Map<String, String> someProperties) {
    Path<?> keyPath = propertiesMap.key();
    Path<?> valuePath = propertiesMap.value();
    List<Predicate> keyValuePairs = new LinkedList<Predicate>();
    for (Map.Entry<String, String> entry : someProperties.entrySet()) {
        Predicate keyPredicate = criteriaBuilder.equal(keyPath, entry.getKey());
        Predicate valuePredicate = criteriaBuilder.equal(valuePath, entry.getValue());
        Predicate keyValuePair = criteriaBuilder.and(keyPredicate, valuePredicate);
        keyValuePairs.add(keyValuePair);
    }
    return criteriaBuilder.or(keyValuePairs.toArray(new Predicate[keyValuePairs.size()]));
}
Example 98
Project: breeze.server.java-master  File: JPACriteriaBuilder.java View source code
@SuppressWarnings("unchecked")
private void addWhere(CriteriaQuery<?> crit, Predicate wherePred) {
    if (wherePred == null)
        return;
    //        CriteriaWrapper critWrapper = new CriteriaWrapper(crit, _entityType);
    //        Criterion cr = toCriterion(crit, wherePred, null);
    //        crit.add(cr);
    // nested path translate, ?Task???"user.name"?filedName, ???Task.user.name??
    //        String[] names = StringUtils.split(filter.fieldName, ".");
    //        Path expression = root.get(names[0]);
    //        for (int i = 1; i < names.length; i++) {
    //            expression = expression.get(names[i]);
    //        }        
    BinaryPredicate breezePred = (BinaryPredicate) wherePred;
    Operator op = breezePred.getOperator();
    String symbol = op.getName();
    Expression expr1 = breezePred.getExpr1();
    Expression expr2 = breezePred.getExpr2();
    String contextAlias = null;
    javax.persistence.criteria.Predicate xpred;
    if (expr1 instanceof PropExpression) {
        PropExpression pexpr1 = (PropExpression) expr1;
        String propPath = pexpr1.getPropertyPath();
        String propName;
        if (pexpr1.getProperty().getParentType().isComplexType()) {
            // don't process the property path in this case.
            propName = propPath;
        } else {
            //crit. _aliasBuilder.getPropertyName(crit, propPath);
            propName = propPath;
        }
        propName = (contextAlias == null) ? propName : contextAlias + "." + propName;
        Path path = _root.get(propName);
        if (expr2 instanceof LitExpression) {
            Object value = ((LitExpression) expr2).getValue();
            if (value == null) {
                if (op == Operator.Equals) {
                    xpred = _cb.isNull(path);
                } else if (op == Operator.NotEquals) {
                    xpred = _cb.isNotNull(path);
                } else {
                    throw new RuntimeException("Binary Predicate with a null value and the " + op.getName() + "operator is not supported .");
                }
            } else if (op == Operator.Equals) {
                xpred = _cb.equal(path, value);
            } else if (op == Operator.NotEquals) {
                xpred = _cb.notEqual(path, value);
            } else if (op == Operator.GreaterThan) {
                xpred = _cb.greaterThan(_root.<Comparable>get(propName), (Comparable) value);
            } else if (op == Operator.GreaterThanOrEqual) {
                xpred = _cb.greaterThanOrEqualTo(_root.<Comparable>get(propName), (Comparable) value);
            } else if (op == Operator.LessThan) {
                xpred = _cb.lessThan(_root.<Comparable>get(propName), (Comparable) value);
            } else if (op == Operator.LessThanOrEqual) {
                xpred = _cb.lessThanOrEqualTo(_root.<Comparable>get(propName), (Comparable) value);
            } else if (op == Operator.In) {
                xpred = path.in((List) value);
            } else if (op == Operator.StartsWith) {
                xpred = _cb.like(path, "" + value + "%");
            } else if (op == Operator.EndsWith) {
                xpred = _cb.like(path, "%" + value);
            } else if (op == Operator.Contains) {
                xpred = _cb.like(path, "%" + value + "%");
            } else {
                throw new RuntimeException("Binary Predicate with the " + op.getName() + "operator is not yet supported.");
            }
        } else {
            String otherPropPath = ((PropExpression) expr2).getPropertyPath();
            Path otherPath = _root.get(otherPropPath);
            if (op == Operator.Equals) {
                xpred = _cb.equal(path, otherPath);
            } else if (op == Operator.NotEquals) {
                xpred = _cb.notEqual(path, otherPath);
            } else if (op == Operator.GreaterThan) {
                xpred = _cb.greaterThan(_root.<Comparable>get(propName), _root.<Comparable>get(otherPropPath));
            } else if (op == Operator.GreaterThanOrEqual) {
                xpred = _cb.greaterThanOrEqualTo(_root.<Comparable>get(propName), _root.<Comparable>get(otherPropPath));
            } else if (op == Operator.LessThan) {
                xpred = _cb.lessThan(_root.<Comparable>get(propName), _root.<Comparable>get(otherPropPath));
            } else if (op == Operator.LessThanOrEqual) {
                xpred = _cb.lessThanOrEqualTo(_root.<Comparable>get(propName), _root.<Comparable>get(otherPropPath));
            } else if (op == Operator.StartsWith) {
                xpred = _cb.like(path, _cb.concat(otherPath, "%"));
            } else if (op == Operator.EndsWith) {
                xpred = _cb.like(path, _cb.concat("%", otherPath));
            } else if (op == Operator.Contains) {
                xpred = _cb.like(path, _cb.concat(_cb.concat("%", otherPath), "%"));
            } else {
                throw new RuntimeException("Property comparison with the " + op.getName() + "operator is not yet supported.");
            }
        }
        crit.where(xpred);
        return;
    } else {
        throw new RuntimeException("Function expressions not yet supported.");
    }
}
Example 99
Project: BusinessManager-master  File: GenericDaoImpl.java View source code
@Override
public List<T> findAll(SingularAttribute<T, ?> orderAttribute, boolean orderAsc, int firstResult, int maxResults, Map<SingularAttribute<T, ?>, Object> filterAttributes, boolean enableLikeSearch) {
    CriteriaBuilder queryBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = queryBuilder.createQuery(getPersistenceClass());
    Root<T> rootQuery = criteriaQuery.from(getPersistenceClass());
    CriteriaQuery<T> select = criteriaQuery.select(rootQuery);
    List<Predicate> predicateList = createFilterList(filterAttributes, enableLikeSearch, queryBuilder, rootQuery);
    select.where(predicateList.toArray(new Predicate[0]));
    if (orderAsc) {
        criteriaQuery.orderBy(queryBuilder.asc(rootQuery.get(orderAttribute)));
    } else {
        criteriaQuery.orderBy(queryBuilder.desc(rootQuery.get(orderAttribute)));
    }
    TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery);
    if (firstResult != -1) {
        typedQuery.setFirstResult(firstResult);
    }
    if (maxResults != -1) {
        typedQuery.setMaxResults(maxResults);
    }
    return typedQuery.getResultList();
}
Example 100
Project: che-master  File: JpaRecipeDao.java View source code
@Override
@Transactional
public List<RecipeImpl> search(String user, List<String> tags, String type, int skipCount, int maxItems) throws ServerException {
    try {
        final EntityManager manager = managerProvider.get();
        final CriteriaBuilder cb = manager.getCriteriaBuilder();
        final CriteriaQuery<RecipeImpl> query = cb.createQuery(RecipeImpl.class);
        final Root<RecipeImpl> fromRecipe = query.from(RecipeImpl.class);
        final ParameterExpression<String> typeParam = cb.parameter(String.class, "recipeType");
        final Predicate checkType = cb.or(cb.isNull(typeParam), cb.equal(fromRecipe.get("type"), typeParam));
        final TypedQuery<RecipeImpl> typedQuery;
        if (tags != null && !tags.isEmpty()) {
            final Join<RecipeImpl, String> tag = fromRecipe.join("tags");
            query.select(cb.construct(RecipeImpl.class, tag.getParent())).where(cb.and(checkType, tag.in(tags))).groupBy(fromRecipe.get("id")).having(cb.equal(cb.count(tag), tags.size()));
            typedQuery = manager.createQuery(query).setParameter("tags", tags);
        } else {
            typedQuery = manager.createQuery(query.where(checkType));
        }
        return typedQuery.setParameter("recipeType", type).setFirstResult(skipCount).setMaxResults(maxItems).getResultList();
    } catch (RuntimeException ex) {
        throw new ServerException(ex.getLocalizedMessage(), ex);
    }
}
Example 101
Project: core-master  File: CodeFragmentManagerImpl.java View source code
public List<CodeFragment> searchCodeFragments(CodeFragment codeFragment, int page, Paginator paginator) {
    // Create a criteria, which we then populate using our prototype code fragment
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CodeFragment> criteria = builder.createQuery(CodeFragment.class);
    Root<CodeFragment> root = criteria.from(CodeFragment.class);
    List<Predicate> predicates = new ArrayList<Predicate>();
    // Only search public code fragements
    predicates.add(builder.isNull(root.get(CodeFragment_.hash)));
    if (!isEmpty(codeFragment.getUser())) {
        predicates.add(builder.equal(root.get(CodeFragment_.user), codeFragment.getUser().toLowerCase().trim()));
    }
    if (codeFragment.getLanguage() != null) {
        predicates.add(builder.equal(root.get(CodeFragment_.language), codeFragment.getLanguage()));
    }
    if (!isEmpty(codeFragment.getText())) {
        predicates.add(builder.like(root.get(CodeFragment_.text), "%" + codeFragment.getText().toLowerCase().trim() + "%"));
    }
    if (codeFragment.getDatetime() != null) {
        predicates.add(builder.between(root.get(CodeFragment_.datetime), codeFragment.getDatetime(), new Date()));
    }
    criteria.where(predicates.toArray(new Predicate[0])).orderBy(builder.desc(root.get(CodeFragment_.datetime)));
    Query q = entityManager.createQuery(criteria);
    int totalRecords = q.getResultList().size();
    // Compute the page
    q.setFirstResult(page * PAGE_SIZE);
    q.setMaxResults(PAGE_SIZE);
    @SuppressWarnings("unchecked") List<CodeFragment> codes = q.getResultList();
    paginator.setPage(page);
    paginator.setRecordsCount(totalRecords);
    paginator.setPagesCount(totalRecords / PAGE_SIZE);
    return codes;
}