Java Code Examples for cz.jirutka.rsql.parser.ast.ComparisonNode

The following examples show how to use cz.jirutka.rsql.parser.ast.ComparisonNode. These examples are extracted from open source projects. 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 Project: gemini   Source File: EntityRefTypeFilterVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private QueryWithParams handleMultipleLogicalKeyEntities(EntityField field, ComparisonNode node, String sqlOperator, FilterVisitorContext filterVisitorContext) {
    List<String> arguments = node.getArguments();
    if (arguments.size() == 1) {
        Entity entityRef = field.getEntityRef();
        String entityName = wrapDoubleQuotes(entityRef.getName().toLowerCase());
        String idName = wrapDoubleQuotes(entityRef.getIdEntityField().getName().toLowerCase());
        String argument = arguments.get(0);

        // we need to parse again the argument if we dont' have a UUID.. since it contains other conditions on keys
        Node rootNode = new RSQLParser().parse(argument);
        QueryWithParams innerQuery = rootNode.accept(this.parentFilterVisitor, FilterVisitorContext.of(entityRef, filterVisitorContext.counterByParameter));
        return new QueryWithParams(String.format("SELECT %1$s.%2$s" +
                "  FROM %1$s WHERE ", entityName, idName)
                + innerQuery.getSql(), innerQuery.getParams());
    }
    throw new GeminiRuntimeException(String.format("EntityRefTypeFilterVisitor unsupported operator %s withRecord for that one argument", node.getOperator().getSymbol()));
}
 
Example 2
Source Project: gemini   Source File: EntityRefTypeFilterVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private QueryWithParams handleSingleLogicalKeyEntity(EntityField field, ComparisonNode node, String sqlOperator, FilterVisitorContext filterVisitorContext) {
    Entity entityRef = field.getEntityRef();
    Entity.LogicalKey logicalKey = entityRef.getLogicalKey();
    EntityField lkField = logicalKey.getLogicalKeyList().get(0);
    List<String> arguments = node.getArguments();
    String parameterName = filterVisitorContext.parameterFor(fieldName(lkField, false));
    String innerFilter = ":" + parameterName;

    List<Object> parameters = arguments.stream().map(a -> resolveArgumentValue(lkField, a)).collect(Collectors.toList());

    String sqlFilter = String.format("" +
                    "SELECT %1$s.%2$s" +
                    "  FROM %1$s " +
                    " WHERE %1$s.%3$s ",
            wrapDoubleQuotes(entityRef.getName().toLowerCase()),
            wrapDoubleQuotes(entityRef.getIdEntityField().getName().toLowerCase()),
            fieldName(lkField, true));
    sqlFilter += String.format(sqlOperator, innerFilter);
    return new QueryWithParams(sqlFilter, Map.of(parameterName, parameters));
}
 
Example 3
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void validateMapParameter(final A propertyEnum, final ComparisonNode node, final String[] graph) {
    if (!propertyEnum.isMap()) {
        return;

    }

    if (!propertyEnum.getSubEntityAttributes().isEmpty()) {
        throw new UnsupportedOperationException(
                "Currently subentity attributes for maps are not supported, alternatively you could use the key/value tuple, defined by SimpleImmutableEntry class");
    }

    // enum.key
    final int minAttributeForMap = 2;
    if (graph.length != minAttributeForMap) {
        throw new RSQLParameterUnsupportedFieldException("The syntax of the given map search parameter field {"
                + node.getSelector() + "} is wrong. Syntax is: fieldname.keyname", new Exception());
    }
}
 
Example 4
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Object convertValueIfNecessary(final ComparisonNode node, final A fieldName, final String value,
        final Path<Object> fieldPath) {
    // in case the value of an rsql query e.g. type==application is an
    // enum we need to handle it separately because JPA needs the
    // correct java-type to build an expression. So String and numeric
    // values JPA can do it by it's own but not for classes like enums.
    // So we need to transform the given value string into the enum
    // class.
    final Class<?> javaType = fieldPath.getJavaType();
    if (javaType != null && javaType.isEnum()) {
        return transformEnumValue(node, value, javaType);
    }
    if (fieldName instanceof FieldValueConverter) {
        return convertFieldConverterValue(node, fieldName, value);
    }

    if (Boolean.TYPE.equals(javaType)) {
        return convertBooleanValue(node, value, javaType);
    }

    return value;
}
 
Example 5
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked", "squid:S2095" })
private static Object transformEnumValue(final ComparisonNode node, final String value,
        final Class<?> javaType) {
    final Class<? extends Enum> tmpEnumType = (Class<? extends Enum>) javaType;
    try {
        return Enum.valueOf(tmpEnumType, value.toUpperCase());
    } catch (final IllegalArgumentException e) {
        // we could not transform the given string value into the enum
        // type, so ignore it and return null and do not filter
        LOGGER.info("given value {} cannot be transformed into the correct enum type {}", value.toUpperCase(),
                javaType);
        LOGGER.debug("value cannot be transformed to an enum", e);

        throw new RSQLParameterUnsupportedFieldException("field {" + node.getSelector()
                + "} must be one of the following values {" + Arrays.stream(tmpEnumType.getEnumConstants())
                        .map(v -> v.name().toLowerCase()).collect(Collectors.toList())
                + "}", e);
    }
}
 
Example 6
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private List<Predicate> mapToPredicate(final ComparisonNode node, final Path<Object> fieldPath,
        final List<String> values, final List<Object> transformedValues, final A enumField,
        final String finalProperty) {

    String value = values.get(0);
    // if lookup is available, replace macros ...
    if (virtualPropertyReplacer != null) {
        value = virtualPropertyReplacer.replace(value);
    }

    final Predicate mapPredicate = mapToMapPredicate(node, fieldPath, enumField);

    final Predicate valuePredicate = addOperatorPredicate(node, getMapValueFieldPath(enumField, fieldPath),
            transformedValues, value, finalProperty, enumField);

    return toSingleList(mapPredicate != null ? cb.and(mapPredicate, valuePredicate) : valuePredicate);
}
 
Example 7
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Predicate mapToMapPredicate(final ComparisonNode node, final Path<Object> fieldPath,
        final A enumField) {
    if (!enumField.isMap()) {
        return null;
    }

    final String[] graph = getSubAttributesFrom(node.getSelector());

    final String keyValue = graph[graph.length - 1];
    if (fieldPath instanceof MapJoin) {
        // Currently we support only string key .So below cast is safe.
        return cb.equal(cb.upper((Expression<String>) (((MapJoin<?, ?, ?>) fieldPath).key())),
                keyValue.toUpperCase());
    }

    final String keyFieldName = enumField.getSubEntityMapTuple().map(Entry::getKey)
            .orElseThrow(() -> new UnsupportedOperationException(
                    "For the fields, defined as Map, only Map java type or tuple in the form of SimpleImmutableEntry are allowed. Neither of those could be found!"));

    return cb.equal(cb.upper(fieldPath.get(keyFieldName)), keyValue.toUpperCase());
}
 
Example 8
Source Project: pnc   Source File: SortRSQLNodeTraveller.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SortInfo visit(ComparisonNode node) {
    SortingDirection sortingDirection;
    List<String> sortingFields = new ArrayList<>();

    if (node.getOperator().equals(ASC)) {
        sortingDirection = SortInfo.SortingDirection.ASC;
    } else if (node.getOperator().equals(DESC)) {
        sortingDirection = SortInfo.SortingDirection.DESC;
    } else {
        throw new UnsupportedOperationException("Unsupported sorting: " + node.getOperator());
    }

    logger.trace("Sorting direction - {}, arguments {}", sortingDirection, node.getArguments());
    for (String argument : node.getArguments()) {
        if ("id".equals(argument)) { // Disable sorting by id
            throw new RSQLException("Sorting by id is not supported.");
        }
        sortingFields.add(toPath.apply(RSQLSelectorPath.get(argument)));
    }
    return new DefaultSortInfo(sortingDirection, sortingFields);
}
 
Example 9
Source Project: pnc   Source File: ComparatorRSQLNodeTraveller.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Comparator<DTO> visit(ComparisonNode node) {
    logger.trace("Sorting direction - {}, arguments {}", node.getOperator(), node.getArguments());
    Comparator<DTO> comparator = null;
    for (String argument : node.getArguments()) {
        Comparator<DTO> comp = Comparator.comparing(dto -> getProperty(dto, argument));
        if (comparator == null) {
            comparator = comp;
        } else {
            comparator = comparator.thenComparing(comp);
        }
    }
    if (comparator == null) {
        throw new RSQLException("No argument for RSQL comparsion found.");
    }
    if (node.getOperator().equals(DESC)) {
        comparator = comparator.reversed();
    }

    return comparator;
}
 
Example 10
@ParameterizedTest
@MethodSource("testVisitComparisonNodeLessThanOrEqualProvider")
void testVisitComparisonNodeLessThanOrEqual(String symbol) {
  String selector = "age";
  String argument = "87";
  ComparisonOperator operator = new ComparisonOperator(symbol);
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query =
      Query.builder()
          .setItem(selector)
          .setOperator(LESS_THAN_OR_EQUAL_TO)
          .setValue(argument)
          .build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example 11
@ParameterizedTest
@MethodSource("testVisitComparisonNodeGreaterThanOrEqualProvider")
void testVisitComparisonNodeGreaterThanOrEqual(String symbol) {
  String selector = "age";
  String argument = "87";
  ComparisonOperator operator = new ComparisonOperator(symbol);
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query =
      Query.builder()
          .setItem(selector)
          .setOperator(GREATER_THAN_OR_EQUAL_TO)
          .setValue(argument)
          .build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example 12
@Test
void testVisitOrNode() {
  String argument0 = "piet";
  ComparisonOperator operator0 = new ComparisonOperator("=q=");
  ComparisonNode node0 = new ComparisonNode(operator0, "*", singletonList(argument0));

  String argument1 = "jan";
  ComparisonOperator operator1 = new ComparisonOperator("=q=");
  ComparisonNode node1 = new ComparisonNode(operator1, "*", singletonList(argument1));

  OrNode orNode = new OrNode(asList(node0, node1));
  Query query =
      Query.builder()
          .setOperator(OR)
          .setValue(
              asList(
                  Query.builder().setOperator(MATCHES).setValue(argument0).build(),
                  Query.builder().setOperator(MATCHES).setValue(argument1).build()))
          .build();
  assertEquals(query, queryRsqlVisitor.visit(orNode));
}
 
Example 13
@Test
void testVisitAndNode() {
  String argument0 = "piet";
  ComparisonOperator operator0 = new ComparisonOperator("=q=");
  ComparisonNode node0 = new ComparisonNode(operator0, "*", singletonList(argument0));

  String argument1 = "jan";
  ComparisonOperator operator1 = new ComparisonOperator("=q=");
  ComparisonNode node1 = new ComparisonNode(operator1, "*", singletonList(argument1));

  AndNode andNode = new AndNode(asList(node0, node1));
  Query query =
      Query.builder()
          .setOperator(AND)
          .setValue(
              asList(
                  Query.builder().setOperator(MATCHES).setValue(argument0).build(),
                  Query.builder().setOperator(MATCHES).setValue(argument1).build()))
          .build();
  assertEquals(query, queryRsqlVisitor.visit(andNode));
}
 
Example 14
private Attribute getAttribute(ComparisonNode node) {
  List<String> args = node.getArguments();
  if (args.size() != 1) {
    throw new MolgenisQueryException(
        String.format(
            "RSQL query value must have exactly one value instead of [%s]",
            StringUtils.join(args, ',')));
  }
  String attrName = args.iterator().next();

  String[] attrTokens = attrName.split("\\.");
  Attribute attr = entityType.getAttribute(attrTokens[0]);
  if (attr == null) {
    throw new UnknownAttributeException(entityType, attrName);
  }
  EntityType entityTypeAtDepth;
  for (int i = 1; i < attrTokens.length; ++i) {
    entityTypeAtDepth = attr.getRefEntity();
    attr = entityTypeAtDepth.getAttribute(attrTokens[i]);
    if (attr == null) {
      throw new UnknownAttributeException(entityTypeAtDepth, attrName);
    }
  }

  return attr;
}
 
Example 15
private Attribute getAttribute(ComparisonNode node) {
  EntityType entityType = repository.getEntityType();
  String attrName = node.getSelector();

  String[] attrTokens = attrName.split("\\.");
  Attribute attr = entityType.getAttribute(attrTokens[0]);
  if (attr == null) {
    throw new UnknownAttributeException(entityType, attrName);
  }
  EntityType entityTypeAtDepth;
  for (int i = 1; i < attrTokens.length; ++i) {
    entityTypeAtDepth = attr.getRefEntity();
    attr = entityTypeAtDepth.getAttribute(attrTokens[i]);
    if (attr == null) {
      throw new UnknownAttributeException(entityTypeAtDepth, attrName);
    }
  }

  return attr;
}
 
Example 16
Source Project: gemini   Source File: EntityRefTypeFilterVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QueryWithParams visit(EntityField field, ComparisonNode node, FilterVisitorContext filterVisitorContext) {
    ComparisonOperator operator = node.getOperator();
    if (supportedOperators.containsKey(operator)) {
        FieldType type = field.getType();
        assert type.equals(FieldType.ENTITY_REF);
        String sqlOperator = supportedOperators.get(operator);

        if (operator.equals(EMPTY_OPERATOR)) {
            return new QueryWithParams(wrapDoubleQuotes(field.getEntity().getName().toLowerCase()) + "." +
                    fieldName(field, true) + sqlOperator, Map.of());
        }

        Entity entityRef = field.getEntityRef();
        Entity.LogicalKey refLogicalKey = entityRef.getLogicalKey();
        assert refLogicalKey != null;
        QueryWithParams innerINQuery;

        List<String> arguments = node.getArguments();
        try {
            innerINQuery = handleUUID(arguments, sqlOperator, filterVisitorContext, entityRef);
        } catch (IllegalArgumentException e) {
            if (refLogicalKey.getLogicalKeyList().size() == 1) {
                innerINQuery = handleSingleLogicalKeyEntity(field, node, sqlOperator, filterVisitorContext);
            } else {
                innerINQuery = handleMultipleLogicalKeyEntities(field, node, sqlOperator, filterVisitorContext);
            }
        }
        String sqlFullString = wrapDoubleQuotes(field.getEntity().getName().toLowerCase()) + "." +
                fieldName(field, true)
                + " IN ( " + innerINQuery.getSql() + " )";
        return new QueryWithParams(sqlFullString, innerINQuery.getParams());

    }
    throw new GeminiRuntimeException(String.format("EntityRefTypeFilterVisitor unsupported operator %s", node.getOperator().getSymbol()));
}
 
Example 17
Source Project: gemini   Source File: BasicTypeFilterVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public QueryWithParams visit(EntityField field, ComparisonNode node, FilterVisitorContext filterVisitorContext) {
    ComparisonOperator operator = node.getOperator();
    List<String> arguments = node.getArguments();
    QueryWithParams singleArg = handleSingleArgumentOperator(field, operator, arguments, filterVisitorContext);
    if (singleArg != null)
        return singleArg;
    QueryWithParams multipleArg = handleMultipleArgumentOperator(field, operator, arguments, filterVisitorContext);
    if (multipleArg == null) {
        throw new GeminiRuntimeException(String.format("Filter not impemented for type %s", field.getType()));
    }
    return multipleArg;
}
 
Example 18
Source Project: rsql-jpa-specification   Source File: RSQLComplexConverter.java    License: MIT License 5 votes vote down vote up
@Override
public Void visit(ComparisonNode node, Map<String, MultiValueMap<String, String>> map) {
	log.debug("visit(node:{},map:{})", node, map);
	String key = node.getSelector();
	ComparisonOperator operator = node.getOperator();
	MultiValueMap<String, String> operatorMap = map.computeIfAbsent(key, k -> CollectionUtils.toMultiValueMap(new HashMap<>()));
	for (String ops : operator.getSymbols()) {
		operatorMap.addAll(ops, node.getArguments());
	}
	return null;
}
 
Example 19
Source Project: dremio-oss   Source File: SearchFilterToQueryConverter.java    License: Apache License 2.0 5 votes vote down vote up
private SearchQuery buildLeafNodeQuery(final ComparisonNode node) throws IllegalArgumentException {
  final IndexKey indexKey = mapping.getKey(node.getSelector());
  final String name = indexKey != null ? indexKey.getIndexFieldName() : null;
  final Class<?> clazz = indexKey != null ? indexKey.getValueType() : null;
  final List<Object> processedArgs = validate(node, name, clazz);

  if (node.getOperator().equals(RSQLOperators.EQUAL)) {
    return createEqualsQuery(clazz, name, processedArgs.get(0),indexKey.getReservedValues());
  } else if (node.getOperator().equals(RSQLOperators.NOT_EQUAL)) {
    return SearchQueryUtils.not(createEqualsQuery(clazz, name, processedArgs.get(0), null));
  } else if (node.getOperator().equals(RSQLOperators.LESS_THAN)) {
    return createRangeQuery(clazz, name, processedArgs.get(0), RSQLOperators.LESS_THAN);
  } else if (node.getOperator().equals(RSQLOperators.LESS_THAN_OR_EQUAL)) {
    return createRangeQuery(clazz, name, processedArgs.get(0), RSQLOperators.LESS_THAN_OR_EQUAL);
  } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN)) {
    return createRangeQuery(clazz, name, processedArgs.get(0), RSQLOperators.GREATER_THAN);
  } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN_OR_EQUAL)) {
    return createRangeQuery(clazz, name, processedArgs.get(0), RSQLOperators.GREATER_THAN_OR_EQUAL);
  } else if (node.getOperator().equals(RSQLOperators.IN)) {
    throw new IllegalArgumentException("IN operator not yet supported");
  } else if (node.getOperator().equals(RSQLOperators.NOT_IN)) {
    throw new IllegalArgumentException("NOT_IN operator not yet supported");
  } else if (node.getOperator().equals(CONTAINS)) {
    return createMatchAllFieldsQuery((String)processedArgs.get(0), mapping);
  } else {
    throw new IllegalArgumentException(format("%s: Invalid search operator %s", visitorName, node.toString()));
  }
}
 
Example 20
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getAndValidatePropertyFieldName(final A propertyEnum, final ComparisonNode node) {

            final String[] graph = getSubAttributesFrom(node.getSelector());

            validateMapParameter(propertyEnum, node, graph);

            // sub entity need minium 1 dot
            if (!propertyEnum.getSubEntityAttributes().isEmpty() && graph.length < 2) {
                throw createRSQLParameterUnsupportedException(node);
            }

            final StringBuilder fieldNameBuilder = new StringBuilder(propertyEnum.getFieldName());

            for (int i = 1; i < graph.length; i++) {

                final String propertyField = graph[i];
                fieldNameBuilder.append(FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR).append(propertyField);

                // the key of map is not in the graph
                if (propertyEnum.isMap() && graph.length == (i + 1)) {
                    continue;
                }

                if (!propertyEnum.containsSubEntityAttribute(propertyField)) {
                    throw createRSQLParameterUnsupportedException(node);
                }
            }

            return fieldNameBuilder.toString();
        }
 
Example 21
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private RSQLParameterUnsupportedFieldException createRSQLParameterUnsupportedException(
        final ComparisonNode node) {
    return new RSQLParameterUnsupportedFieldException(
            "The given search parameter field {" + node.getSelector()
                    + "} does not exist, must be one of the following fields {" + getExpectedFieldList() + "}",
            new Exception());
}
 
Example 22
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
// Exception squid:S2095 - see
// https://jira.sonarsource.com/browse/SONARJAVA-1478
@SuppressWarnings({ "squid:S2095" })
public List<Predicate> visit(final ComparisonNode node, final String param) {
    A fieldName = null;
    try {
        fieldName = getFieldEnumByName(node);
    } catch (final IllegalArgumentException e) {
        throw new RSQLParameterUnsupportedFieldException("The given search parameter field {"
                + node.getSelector() + "} does not exist, must be one of the following fields {"
                + Arrays.stream(enumType.getEnumConstants()).map(v -> v.name().toLowerCase())
                        .collect(Collectors.toList())
                + "}", e);

    }
    final String finalProperty = getAndValidatePropertyFieldName(fieldName, node);

    final List<String> values = node.getArguments();
    final List<Object> transformedValues = new ArrayList<>();
    final Path<Object> fieldPath = getFieldPath(fieldName, finalProperty);

    for (final String value : values) {
        transformedValues.add(convertValueIfNecessary(node, fieldName, value, fieldPath));
    }

    this.joinsNeeded = this.joinsNeeded || areJoinsNeeded(node);

    return mapToPredicate(node, fieldPath, node.getArguments(), transformedValues, fieldName, finalProperty);
}
 
Example 23
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private A getFieldEnumByName(final ComparisonNode node) {
    String enumName = node.getSelector();
    final String[] graph = getSubAttributesFrom(enumName);
    if (graph.length != 0) {
        enumName = graph[0];
    }
    LOGGER.debug("get fieldidentifier by name {} of enum type {}", enumName, enumType);
    return Enum.valueOf(enumType, enumName.toUpperCase());
}
 
Example 24
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Object convertBooleanValue(final ComparisonNode node, final String value, final Class<?> javaType) {
    try {
        return simpleTypeConverter.convertIfNecessary(value, javaType);
    } catch (final TypeMismatchException e) {
        throw new RSQLParameterSyntaxException(
                "The value of the given search parameter field {" + node.getSelector()
                        + "} is not well formed. Only a boolean (true or false) value will be expected {",
                e);
    }
}
 
Example 25
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object convertFieldConverterValue(final ComparisonNode node, final A fieldName, final String value) {
    final Object convertedValue = ((FieldValueConverter) fieldName).convertValue(fieldName, value);
    if (convertedValue == null) {
        throw new RSQLParameterUnsupportedFieldException(
                "field {" + node.getSelector() + "} must be one of the following values {"
                        + Arrays.toString(((FieldValueConverter) fieldName).possibleValues(fieldName)) + "}",
                null);
    } else {
        return convertedValue;
    }
}
 
Example 26
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Predicate addOperatorPredicate(final ComparisonNode node, final Path<Object> fieldPath,
        final List<Object> transformedValues, final String value, final String finalProperty,
        final A enumField) {

    // only 'equal' and 'notEqual' can handle transformed value like
    // enums. The JPA API cannot handle object types for greaterThan etc
    // methods.
    final Object transformedValue = transformedValues.get(0);
    final String operator = node.getOperator().getSymbol();

    switch (operator) {
    case "==":
        return getEqualToPredicate(transformedValue, fieldPath);
    case "!=":
        return getNotEqualToPredicate(transformedValue, fieldPath, finalProperty, enumField);
    case "=gt=":
        return cb.greaterThan(pathOfString(fieldPath), value);
    case "=ge=":
        return cb.greaterThanOrEqualTo(pathOfString(fieldPath), value);
    case "=lt=":
        return cb.lessThan(pathOfString(fieldPath), value);
    case "=le=":
        return cb.lessThanOrEqualTo(pathOfString(fieldPath), value);
    case "=in=":
        return getInPredicate(transformedValues, fieldPath);
    case "=out=":
        return getOutPredicate(transformedValues, finalProperty, enumField, fieldPath);
    default:
        throw new RSQLParameterSyntaxException(
                "operator symbol {" + operator + "} is either not supported or not implemented");
    }
}
 
Example 27
Source Project: pnc   Source File: RSQLNodeTraveller.java    License: Apache License 2.0 5 votes vote down vote up
public T visit(Node node) {
    // remember overloading is chosen based on static type.
    if (node instanceof LogicalNode) {
        return visit((LogicalNode) node);
    } else if (node instanceof ComparisonNode) {
        return visit((ComparisonNode) node);
    } else {
        throw new UnsupportedOperationException("Did you invent 3rd type of the node?");
    }
}
 
Example 28
Source Project: pnc   Source File: RSQLNodeTraveller.java    License: Apache License 2.0 5 votes vote down vote up
public T visit(Node node) {
    // remember overloading is chosen based on static type.
    if (node instanceof LogicalNode) {
        return visit((LogicalNode) node);
    } else if (node instanceof ComparisonNode) {
        return visit((ComparisonNode) node);
    } else {
        throw new UnsupportedOperationException("Did you invent 3rd type of the node?");
    }
}
 
Example 29
@Override
public Query visit(ComparisonNode node) {
  String item = toItem(node);
  Operator operator = toOperator(node);
  Object value = toValue(node, operator);
  return Query.builder().setItem(item).setOperator(operator).setValue(value).build();
}
 
Example 30
private static Object toValue(ComparisonNode node, Operator operator) {
  Object value;

  List<String> arguments = getNormalizedArguments(node);
  switch (operator) {
    case EQUALS:
    case NOT_EQUALS:
      value = arguments.get(0);
      break;
    case MATCHES:
    case SEARCH_QUERY:
    case CONTAINS:
    case LESS_THAN:
    case LESS_THAN_OR_EQUAL_TO:
    case GREATER_THAN:
    case GREATER_THAN_OR_EQUAL_TO:
      value = arguments.get(0);
      if (value == null) {
        throw new MissingRsqlValueException(operator);
      }
      break;
    case IN:
    case NOT_IN:
      value = arguments;
      break;
    case AND:
    case OR:
    default:
      throw new UnexpectedEnumException(operator);
  }

  return value;
}