com.mysema.query.types.path.PathBuilder Java Examples

The following examples show how to use com.mysema.query.types.path.PathBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return where clause expression for {@code Boolean} fields by transforming
 * the given {@code searchStr} to {@code Boolean} before check its value.
 * <p/>
 * Expr: {@code entityPath.fieldName eq (TRUE | FALSE)}
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the boolean value to find, may be null. Supported string
 *        are: si, yes, true, on, no, false, off
 * @return BooleanExpression
 */
public static <T> BooleanExpression createBooleanExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr) {
    if (StringUtils.isBlank(searchStr)) {
        return null;
    }

    Boolean value = null;

    // I18N: Spanish (normalize search value: trim start-end and lower case)
    if ("si".equals(StringUtils.trim(searchStr).toLowerCase())) {
        value = Boolean.TRUE;
    }
    else {
        value = BooleanUtils.toBooleanObject(searchStr);
    }

    // if cannot parse to boolean or null input
    if (value == null) {
        return null;
    }

    BooleanExpression expression = entityPath.getBoolean(fieldName).eq(
            value);
    return expression;
}
 
Example #2
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return an expression for {@code entityPath.fieldName} (for Strings) with
 * the {@code operator} or "equal" by default.
 * <p/>
 * Expr: {@code entityPath.fieldName eq searchObj}
 * 
 * @param entityPath
 * @param fieldName
 * @param searchObj
 * @param operator
 * @return
 */
public static <T> BooleanExpression createStringExpression(
        PathBuilder<T> entityPath, String fieldName, Object searchObj,
        String operator) {
    if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
        return entityPath.getString(fieldName).goe((String) searchObj);
    }
    else if (StringUtils.equalsIgnoreCase(operator, "gt")) {
        return entityPath.getString(fieldName).gt((String) searchObj);
    }
    else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
        return entityPath.getString(fieldName).loe((String) searchObj);
    }
    else if (StringUtils.equalsIgnoreCase(operator, "lt")) {
        return entityPath.getString(fieldName).lt((String) searchObj);
    }
    else if (StringUtils.equalsIgnoreCase(operator, "like")) {
        return entityPath.getString(fieldName).like((String) searchObj);
    }
    return entityPath.get(fieldName).eq(searchObj);
}
 
Example #3
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return an expression for {@code entityPath.fieldName} (for Booleans) with
 * the {@code operator} or "equal" by default.
 * <p/>
 * Expr: {@code entityPath.fieldName eq searchObj}
 * 
 * @param entityPath
 * @param fieldName
 * @param searchObj
 * @param operator
 * @return
 */
public static <T> BooleanExpression createBooleanExpression(
        PathBuilder<T> entityPath, String fieldName, Object searchObj,
        String operator) {
    Boolean value = BooleanUtils.toBooleanObject((String) searchObj);
    if (value != null) {
        if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
            return entityPath.getBoolean(fieldName).goe(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, "gt")) {
            return entityPath.getBoolean(fieldName).gt(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
            return entityPath.getBoolean(fieldName).loe(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, "lt")) {
            return entityPath.getBoolean(fieldName).lt(value);
        }
    }
    return entityPath.get(fieldName).eq(searchObj);
}
 
Example #4
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E> BooleanBuilder createPredicateByIn(PathBuilder<T> entity,
        String fieldName, Set<E> values) {

    // Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder predicate = new BooleanBuilder();
    if (StringUtils.isEmpty(fieldName) || values.isEmpty()) {
        return predicate;
    }

    // Build the predicate
    predicate.and(createCollectionExpression(entity, fieldName, values));

    return predicate;
}
 
Example #5
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> BooleanExpression createBooleanExpression(
        PathBuilder<T> entityPath, String fieldName, Object searchObj,
        String operator) {
    Boolean value = BooleanUtils.toBooleanObject((String) searchObj);
    if (value != null) {
        if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
            return entityPath.getBoolean(fieldName).goe(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, "gt")) {
            return entityPath.getBoolean(fieldName).gt(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
            return entityPath.getBoolean(fieldName).loe(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, "lt")) {
            return entityPath.getBoolean(fieldName).lt(value);
        }
    }
    return entityPath.get(fieldName).eq(searchObj);
}
 
Example #6
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(
        Class<T> entityClass,
        Map<String, List<String>> filterByAssociations,
        Map<String, List<String>> orderByAssociations,
        DatatablesCriterias datatablesCriterias,
        BooleanBuilder basePredicate, boolean distinct,
        Object[] rowsOnTopIds) throws IllegalArgumentException {

    Assert.notNull(entityClass);

    // Query DSL builder
    PathBuilder<T> entity = new PathBuilder<T>(entityClass, "entity");

    return findByCriteria(entity, filterByAssociations,
            orderByAssociations, datatablesCriterias, basePredicate,
            distinct, rowsOnTopIds);
}
 
Example #7
Source File: PermissionService.java    From spring-boot-practice with Apache License 2.0 6 votes vote down vote up
public Page<Permission> findAllByRoleId(Integer id, Pageable pageable) {
    QRole role = QRole.role;
    Predicate predicate = role.id.eq(id);

    PathBuilder<Permission> builder = new PathBuilder<Permission>(Permission.class, QPermission.permission.getMetadata());
    Querydsl querydsl = new Querydsl(em, builder);

    JPQLQuery countQuery = createQuery(predicate);
    JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));

    Path<Permission> path = QPermission.permission;
    Long total = countQuery.count();
    List<Permission> content = total > pageable.getOffset() ? query.list(path) : Collections.<Permission>emptyList();

    return new PageImpl<Permission>(content, pageable, total);
}
 
Example #8
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> Class<?> getFieldType1(String fieldName, PathBuilder<T> entity) {
    Class<?> entityType = entity.getType();
    String fieldNameToFindType = fieldName;

    // Makes the array of classes to find fieldName agains them
    Class<?>[] classArray = ArrayUtils.<Class<?>> toArray(entityType);
    if (fieldName.contains(SEPARATOR_FIELDS)) {
        String[] fieldNameSplitted = StringUtils.split(fieldName,
                SEPARATOR_FIELDS);
        for (int i = 0; i < fieldNameSplitted.length - 1; i++) {
            Class<?> fieldType = BeanUtils.findPropertyType(
                    fieldNameSplitted[i],
                    ArrayUtils.<Class<?>> toArray(entityType));
            classArray = ArrayUtils.add(classArray, fieldType);
            entityType = fieldType;
        }
        fieldNameToFindType = fieldNameSplitted[fieldNameSplitted.length - 1];
    }

    return BeanUtils.findPropertyType(fieldNameToFindType, classArray);
}
 
Example #9
Source File: PermissionService.java    From spring-boot-practice with Apache License 2.0 6 votes vote down vote up
public Page<Permission> findAllByRoleId(Integer id, Pageable pageable) {
    QRole role = QRole.role;
    Predicate predicate = role.id.eq(id);

    PathBuilder<Permission> builder = new PathBuilder<Permission>(Permission.class, QPermission.permission.getMetadata());
    Querydsl querydsl = new Querydsl(em, builder);

    JPQLQuery countQuery = createQuery(predicate);
    JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));

    Path<Permission> path = QPermission.permission;
    Long total = countQuery.count();
    List<Permission> content = total > pageable.getOffset() ? query.list(path) : Collections.<Permission>emptyList();

    return new PageImpl<Permission>(content, pageable, total);
}
 
Example #10
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(
        Class<T> entityClass,
        Map<String, List<String>> filterByAssociations,
        Map<String, List<String>> orderByAssociations,
        DatatablesCriterias datatablesCriterias,
        BooleanBuilder basePredicate, boolean distinct)
        throws IllegalArgumentException {

    Assert.notNull(entityClass);

    // Query DSL builder
    PathBuilder<T> entity = new PathBuilder<T>(entityClass, "entity");

    return findByCriteria(entity, filterByAssociations,
            orderByAssociations, datatablesCriterias, basePredicate,
            distinct, null);
}
 
Example #11
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E extends Comparable<?>> OrderSpecifier<?> createOrderSpecifier(
        PathBuilder<T> entityPath, String fieldName, Class<E> fieldType,
        Order order) {
    OrderSpecifier<?> orderBy = null;

    // Get the OrderSpecifier
    if (order == Order.ASC) {
        orderBy = entityPath.getComparable(fieldName, fieldType).asc();
    }
    else if (order == Order.DESC) {
        orderBy = entityPath.getComparable(fieldName, fieldType).desc();
    }
    return orderBy;
}
 
Example #12
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create an order-by-element in a Query instance
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param fieldType Property value {@code Class}. Must implements
 *        {@link Comparable}
 * @param order ascending or descending order
 * @return
 */
public static <T, E extends Comparable<?>> OrderSpecifier<?> createOrderSpecifier(
        PathBuilder<T> entityPath, String fieldName, Class<E> fieldType,
        Order order) {
    OrderSpecifier<?> orderBy = null;

    // Get the OrderSpecifier
    if (order == Order.ASC) {
        orderBy = entityPath.getComparable(fieldName, fieldType).asc();
    }
    else if (order == Order.DESC) {
        orderBy = entityPath.getComparable(fieldName, fieldType).desc();
    }
    return orderBy;
}
 
Example #13
Source File: CollectorItemRepository.java    From hygieia-core with Apache License 2.0 5 votes vote down vote up
default Iterable<CollectorItem> findAllByOptionMapAndCollectorIdsIn(Map<String, Object> options, List<ObjectId> collectorIds) {
    PathBuilder<CollectorItem> path = new PathBuilder<>(CollectorItem.class, "collectorItem");
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(path.get("collectorId", ObjectId.class).in(collectorIds));
    options.forEach((key, value) -> builder.and(Objects.isNull(value)?path.get("options", Map.class).get(key, Object.class).isNull():path.get("options", Map.class).get(key, Object.class).eq(value)));
    return findAll(builder.getValue());
}
 
Example #14
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E> BooleanExpression createCollectionExpression(
        PathBuilder<T> entityPath, String fieldName, Collection<E> values) {
    if (StringUtils.isEmpty(fieldName) || values.isEmpty()) {
        return null;
    }

    if (values.size() > 500) {
        BooleanExpression expression = null;
        Iterable<List<E>> collectionParts = Iterables
                .partition(values, 500);
        for (List<E> part : collectionParts) {
            if (expression == null) {
                expression = doCreateCollectionExpression(entityPath,
                        fieldName, part);
            }
            else {
                expression = expression.or(doCreateCollectionExpression(
                        entityPath, fieldName, part));
            }
        }
        return expression;
    }
    else {
        return doCreateCollectionExpression(entityPath, fieldName, values);
    }
}
 
Example #15
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public <T> BooleanExpression createDateExpression(
        PathBuilder<T> entityPath, String fieldName, Object searchObj,
        String operator, Class<?> fieldType) {
    DatePath<Date> dateExpression = entityPath.getDate(fieldName,
            (Class<Date>) fieldType);
    try {
        Date value = DateUtils.parseDateStrictly((String) searchObj,
                FULL_DATE_PATTERNS);
        if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
            return dateExpression.goe(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, "gt")
                || StringUtils.equalsIgnoreCase(operator, "after")) {
            return dateExpression.gt(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
            return dateExpression.loe(value);
        }
        else if (StringUtils.equalsIgnoreCase(operator, "lt")
                || StringUtils.equalsIgnoreCase(operator, "before")) {
            return dateExpression.lt(value);
        }
    }
    catch (ParseException e) {
        return entityPath.get(fieldName).eq(searchObj);
    }
    return entityPath.get(fieldName).eq(searchObj);
}
 
Example #16
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(
        PathBuilder<T> entity, DatatablesCriterias datatablesCriterias,
        BooleanBuilder basePredicate) throws IllegalArgumentException {
    return findByCriteria(entity, null, null, datatablesCriterias,
            basePredicate, false, null);
}
 
Example #17
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> BooleanExpression createStringExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    BooleanExpression expression = entityPath.getString(fieldName).lower()
            .eq(searchStr.toLowerCase());
    return expression;
}
 
Example #18
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public <T, N extends Number & Comparable<?>> BooleanExpression createNumberExpressionEqual(
        PathBuilder<T> entityPath, String fieldName, Class<N> fieldType,
        TypeDescriptor descriptor, String searchStr) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    NumberPath<N> numberExpression = entityPath.getNumber(fieldName,
            fieldType);

    TypeDescriptor strDesc = STRING_TYPE_DESCRIPTOR;

    if (conversionService != null) {
        try {
            return numberExpression.eq((N) conversionService.convert(
                    searchStr, strDesc, descriptor));
        }
        catch (ConversionException ex) {
            return numberExpression.stringValue().like(
                    "%".concat(searchStr).concat("%"));
        }
    }
    else {
        return numberExpression.stringValue().like(
                "%".concat(searchStr).concat("%"));
    }
}
 
Example #19
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return where clause expression for number properties by casting it to
 * string before check its value.
 * <p/>
 * Querydsl Expr:
 * {@code entityPath.fieldName.stringValue() eq searchStr
 * Database operation:
 * {@code str(entity.fieldName) = searchStr
 * <p/>
 * Like operation is case sensitive.
 *
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the value to find, may be null
 * @return PredicateOperation
 */
@SuppressWarnings("unchecked")
public static <T, N extends java.lang.Number & java.lang.Comparable<?>> BooleanExpression createNumberExpressionEqual(
        PathBuilder<T> entityPath, String fieldName, Class<N> fieldType,
        TypeDescriptor descriptor, String searchStr,
        ConversionService conversionService) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    NumberPath<N> numberExpression = entityPath.getNumber(fieldName,
            fieldType);

    TypeDescriptor strDesc = STRING_TYPE_DESCRIPTOR;

    if (conversionService != null) {
        try {
            return numberExpression.eq((N) conversionService.convert(
                    searchStr, strDesc, descriptor));
        }
        catch (ConversionException ex) {
            return numberExpression.stringValue().like(
                    "%".concat(searchStr).concat("%"));
        }
    }
    else {
        return numberExpression.stringValue().like(
                "%".concat(searchStr).concat("%"));
    }
}
 
Example #20
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> BooleanExpression createBooleanExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr) {
    if (StringUtils.isBlank(searchStr)) {
        return null;
    }

    Boolean value = null;

    // I18N: Spanish (normalize search value: trim start-end and lower case)
    if ("si".equals(StringUtils.trim(searchStr).toLowerCase())) {
        value = Boolean.TRUE;
    }
    else {
        value = BooleanUtils.toBooleanObject(searchStr);
    }

    // if cannot parse to boolean or null input
    if (value == null) {
        return null;
    }

    BooleanExpression expression = entityPath.getBoolean(fieldName).eq(
            value);
    return expression;
}
 
Example #21
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> Predicate createSearchExpression(PathBuilder<T> entityPath,
        String fieldName, String searchStr) {

    TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(String.format(
                "Can't found field '%s' on entity '%s'", fieldName,
                entityPath.getType()));
    }
    Class<?> fieldType = descriptor.getType();

    // Check for field type in order to delegate in custom-by-type
    // create expression method
    if (String.class == fieldType) {
        return createStringLikeExpression(entityPath, fieldName, searchStr);
    }
    else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpression(entityPath, fieldName, searchStr);
    }
    else if (Number.class.isAssignableFrom(fieldType)
            || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenerics(entityPath, fieldName,
                fieldType, descriptor, searchStr);
    }
    else if (Date.class.isAssignableFrom(fieldType)
            || Calendar.class.isAssignableFrom(fieldType)) {
        BooleanExpression expression = createDateExpression(entityPath,
                fieldName, (Class<Date>) fieldType, searchStr);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr,
                (Class<? extends Enum>) fieldType);
    }
    return null;
}
 
Example #22
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a WHERE clause by the intersection of the given search-arguments
 * 
 * @param entity Entity {@link PathBuilder}. It represents the entity for
 *        class generation and alias-usage for path generation.
 *        <p/>
 *        Example: To retrieve a {@code Customer} with the first name 'Bob'
 *        entity must be a {@link PathBuilder} created for {@code Customer}
 *        class and searchArgs must contain the entry
 *        {@code 'firstName':'Bob'}
 * @param searchArgs Search arguments to be used to create the WHERE clause.
 *        It can contain {@code _operator_} entries for each field that want
 *        to use its own operator. By default {@code EQUALS} operator is
 *        used.
 *        <p/>
 *        Operator entry example: {@code _operator_weight = LT} the
 *        expression for {@code weight} field will do a less-than value
 *        comparison
 * @param conversionService required to transform values
 * @return the WHERE clause
 */
public static <T> BooleanBuilder createPredicateByAnd(
        PathBuilder<T> entity, Map<String, Object> searchArgs,
        ConversionService conversionService) {

    // Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder predicate = new BooleanBuilder();
    if (searchArgs == null || searchArgs.isEmpty()) {
        return predicate;
    }

    // Build the predicate
    for (Entry<String, Object> entry : searchArgs.entrySet()) {
        String key = entry.getKey();
        // can
        // contain "_operator_"
        // entries for each
        // field
        Object valueToSearch = entry.getValue();
        String operator = (String) searchArgs.get(OPERATOR_PREFIX
                .concat(key));

        // If value to search is a collection, creates a predicate for
        // each object of the collection
        if (valueToSearch instanceof Collection) {
            @SuppressWarnings("unchecked")
            Collection<Object> valueColl = (Collection<Object>) valueToSearch;
            for (Object valueObj : valueColl) {
                predicate.and(createObjectExpression(entity, key, valueObj,
                        operator, conversionService));
            }
        }
        else {
            predicate.and(createObjectExpression(entity, key,
                    valueToSearch, operator, conversionService));
        }
    }
    return predicate;
}
 
Example #23
Source File: QuerydslUtilsBeanGeoImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method to create Bounding box intersects expression
 * 
 * @param entityPath
 * @param boundingBox
 * @param fieldName
 * @return
 */
public static <T> Predicate createIntersectsExpression(
        PathBuilder<T> entityPath, String fieldName, Geometry boundingBox) {
    JTSPolygonPath<Polygon> polygonPath = new JTSPolygonPath<Polygon>(
            entityPath, fieldName);
    BooleanExpression intersectsExpression = polygonPath
            .intersects(boundingBox);
    return intersectsExpression;
}
 
Example #24
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Utility for constructing where clause expressions.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code name} in {@code Pet} entity, {@code firstName} in
 *        {@code Pet.owner} entity.
 * @param fieldType Property value {@code Class}
 * @param searchStr the value to find, may be null
 * @return Predicate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Predicate createExpression(PathBuilder<T> entityPath,
        String fieldName, String searchStr,
        ConversionService conversionService) {

    TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(String.format(
                "Can't found field '%s' on entity '%s'", fieldName,
                entityPath.getType()));
    }
    Class<?> fieldType = descriptor.getType();

    // Check for field type in order to delegate in custom-by-type
    // create expression method
    if (String.class == fieldType) {
        return createStringLikeExpression(entityPath, fieldName, searchStr);
    }
    else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpression(entityPath, fieldName, searchStr);
    }
    else if (Number.class.isAssignableFrom(fieldType)
            || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenerics(entityPath, fieldName,
                fieldType, descriptor, searchStr, conversionService);
    }
    else if (Date.class.isAssignableFrom(fieldType)
            || Calendar.class.isAssignableFrom(fieldType)) {
        BooleanExpression expression = createDateExpression(entityPath,
                fieldName, (Class<Date>) fieldType, searchStr);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr,
                (Class<? extends Enum>) fieldType);
    }
    return null;
}
 
Example #25
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> BooleanBuilder createPredicateByAnd(PathBuilder<T> entity,
        Map<String, Object> searchArgs) {

    // Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder predicate = new BooleanBuilder();
    if (searchArgs == null || searchArgs.isEmpty()) {
        return predicate;
    }

    // Build the predicate
    for (Entry<String, Object> entry : searchArgs.entrySet()) {
        String key = entry.getKey();
        // can
        // contain "_operator_"
        // entries for each
        // field
        Object valueToSearch = entry.getValue();
        String operator = (String) searchArgs.get(OPERATOR_PREFIX
                .concat(key));

        // If value to search is a collection, creates a predicate for
        // each object of the collection
        if (valueToSearch instanceof Collection) {
            @SuppressWarnings("unchecked")
            Collection<Object> valueColl = (Collection<Object>) valueToSearch;
            for (Object valueObj : valueColl) {
                predicate.and(createObjectExpression(entity, key, valueObj,
                        operator));
            }
        }
        else {
            predicate.and(createObjectExpression(entity, key,
                    valueToSearch, operator));
        }
    }
    return predicate;
}
 
Example #26
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(
        PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations,
        Map<String, List<String>> orderByAssociations,
        DatatablesCriterias datatablesCriterias,
        BooleanBuilder basePredicate, boolean distinct)
        throws IllegalArgumentException {

    return findByCriteria(entity, null, null, datatablesCriterias,
            basePredicate, false, null);
}
 
Example #27
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(
        PathBuilder<T> entity, DatatablesCriterias datatablesCriterias,
        BooleanBuilder basePredicate, Object[] rowsOnTopIds)
        throws IllegalArgumentException {
    return findByCriteria(entity, null, null, datatablesCriterias,
            basePredicate, false, rowsOnTopIds);
}
 
Example #28
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> BooleanExpression createObjectExpression(
        PathBuilder<T> entityPath, String fieldName, Object searchObj) {
    return createObjectExpression(entityPath, fieldName, searchObj, null);

}
 
Example #29
Source File: CollectorItemRepository.java    From hygieia-core with Apache License 2.0 4 votes vote down vote up
default Iterable<CollectorItem> findAllByOptionNameValue(String optionName, String optionValue) {
    PathBuilder<CollectorItem> path = new PathBuilder<>(CollectorItem.class, "collectorItem");
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(path.get("options", Map.class).get(optionName, String.class).eq(optionValue));
    return findAll(builder.getValue());
}
 
Example #30
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Return where clause expression for {@code Boolean} fields by transforming
 * the given {@code searchStr} to {@code Boolean} before check its value.
 * <p/>
 * Expr: {@code entityPath.fieldName eq (TRUE | FALSE)}
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the boolean value to find, may be null. Supported string
 *        are: si, yes, true, on, no, false, off
 * @return BooleanExpression
 */
public static <T> BooleanExpression createBooleanExpressionWithOperators(
        PathBuilder<T> entityPath, String fieldName, String searchStr,
        ConversionService conversionService, MessageSource messageSource) {
    if (StringUtils.isBlank(searchStr)) {
        return null;
    }

    // Getting all operations
    String trueOperation = "TRUE";
    String falseOperation = "FALSE";
    String isNullOperation = OPERATOR_ISNULL;
    String isNotNullOperation = OPERATOR_NOTNULL;

    if (messageSource != null) {
        trueOperation = messageSource.getMessage(
                "global.filters.operations.boolean.true", null,
                LocaleContextHolder.getLocale());
        falseOperation = messageSource.getMessage(
                "global.filters.operations.boolean.false", null,
                LocaleContextHolder.getLocale());
        isNullOperation = messageSource.getMessage(G_FIL_OPE_ISNULL, null,
                LocaleContextHolder.getLocale());
        isNotNullOperation = messageSource.getMessage(G_FIL_OPE_NOTNULL,
                null, LocaleContextHolder.getLocale());
    }

    // If written function is TRUE
    Pattern trueOperator = Pattern.compile(String.format("%s",
            trueOperation));
    Matcher trueMatcher = trueOperator.matcher(searchStr);

    if (trueMatcher.matches()) {
        return entityPath.getBoolean(fieldName).eq(Boolean.TRUE);
    }

    // If written function is FALSE
    Pattern falseOperator = Pattern.compile(String.format("%s",
            falseOperation));
    Matcher falseMatcher = falseOperator.matcher(searchStr);

    if (falseMatcher.matches()) {
        return entityPath.getBoolean(fieldName).eq(Boolean.FALSE);
    }

    // If written expression is ISNULL operation
    Pattern isNullOperator = Pattern.compile(String.format("%s",
            isNullOperation));
    Matcher isNullMatcher = isNullOperator.matcher(searchStr);
    if (isNullMatcher.matches()) {
        return entityPath.getBoolean(fieldName).isNull();

    }

    // If written expression is ISNOTNULL operation
    Pattern isNotNullOperator = Pattern.compile(String.format("%s",
            isNotNullOperation));
    Matcher isNotNullMatcher = isNotNullOperator.matcher(searchStr);
    if (isNotNullMatcher.matches()) {
        return entityPath.getBoolean(fieldName).isNotNull();

    }

    return null;
}