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

The following examples show how to use cz.jirutka.rsql.parser.ast.ComparisonNode. 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: RSQLUtility.java    From hawkbit with 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 #2
Source File: MolgenisRSQLVisitor.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #3
Source File: AggregateQueryRsqlVisitor.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #4
Source File: RSQLUtility.java    From hawkbit with 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 #5
Source File: EntityRefTypeFilterVisitor.java    From gemini with 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 #6
Source File: EntityRefTypeFilterVisitor.java    From gemini with 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 #7
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #8
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #9
Source File: RSQLUtility.java    From hawkbit with 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 #10
Source File: RSQLUtility.java    From hawkbit with 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 #11
Source File: RSQLUtility.java    From hawkbit with 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 #12
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #13
Source File: SortRSQLNodeTraveller.java    From pnc with 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 #14
Source File: ComparatorRSQLNodeTraveller.java    From pnc with 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 #15
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #16
Source File: QueryConverterTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testCreateQuery() {
  String rsqlQuery = "item==value";
  ComparisonNode node =
      new ComparisonNode(new ComparisonOperator("=="), "item", singletonList("value"));
  Query query = Query.builder().setItem("item").setOperator(Operator.EQUALS).build();
  when(node.accept(rsqlVisitor)).thenReturn(query);
  assertEquals(query, queryConverter.convert(rsqlQuery));
  verify(rsqlVisitor).visit(node, null);
}
 
Example #17
Source File: PermissionRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisit2() {
  ComparisonNode comparisonNode =
      new ComparisonNode(
          new ComparisonOperator("=in=", true), "role", Arrays.asList("role1", "role2"));
  assertEquals(
      new PermissionsQuery(emptyList(), asList("role1", "role2")), visitor.visit(comparisonNode));
}
 
Example #18
Source File: PermissionRsqlVisitor.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public PermissionsQuery visit(OrNode orNode) {
  List<Node> nodes = orNode.getChildren();
  PermissionsQuery permissionsQuery = new PermissionsQuery();
  if (nodes.size() == 2) {
    for (Node node : nodes) {
      if (node instanceof ComparisonNode) {
        setQuery((ComparisonNode) node, permissionsQuery);
      } else {
        throw new UnsupportedOperationException("invalide node");
      }
    }
  }
  return permissionsQuery;
}
 
Example #19
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeEquals() {
  String selector = "name";
  String argument = "piet";
  ComparisonOperator operator = new ComparisonOperator("==");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query = Query.builder().setItem(selector).setOperator(EQUALS).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #20
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("testVisitComparisonNodeLessThanProvider")
void testVisitComparisonNodeLessThan(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).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #21
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeContains() {
  String selector = "name";
  String argument = "piet";
  ComparisonOperator operator = new ComparisonOperator("=like=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query =
      Query.builder().setItem(selector).setOperator(CONTAINS).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #22
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeSearchQueryAllSelector() {
  String selector = "*";
  String argument = "piet";
  ComparisonOperator operator = new ComparisonOperator("=sq=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query =
      Query.builder().setItem(null).setOperator(SEARCH_QUERY).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #23
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeSearchQueryNull() {
  String selector = "name";
  String argument = "";
  ComparisonOperator operator = new ComparisonOperator("=sq=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  assertThrows(RuntimeException.class, () -> queryRsqlVisitor.visit(node));
}
 
Example #24
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeSearchQuery() {
  String selector = "name";
  String argument = "piet";
  ComparisonOperator operator = new ComparisonOperator("=sq=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query =
      Query.builder().setItem(selector).setOperator(SEARCH_QUERY).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #25
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeMatchesAllSelector() {
  String selector = "*";
  String argument = "piet";
  ComparisonOperator operator = new ComparisonOperator("=q=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query = Query.builder().setItem(null).setOperator(MATCHES).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #26
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeMatchesNull() {
  String selector = "name";
  String argument = "";
  ComparisonOperator operator = new ComparisonOperator("=q=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  assertThrows(RuntimeException.class, () -> queryRsqlVisitor.visit(node));
}
 
Example #27
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeMatches() {
  String selector = "name";
  String argument = "piet";
  ComparisonOperator operator = new ComparisonOperator("=q=");
  ComparisonNode node = new ComparisonNode(operator, selector, singletonList(argument));

  Query query = Query.builder().setItem(selector).setOperator(MATCHES).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #28
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeNotIn() {
  String selector = "name";
  List<String> arguments = asList("jan", "piet");
  ComparisonOperator operator = new ComparisonOperator("=out=", true);
  ComparisonNode node = new ComparisonNode(operator, selector, arguments);

  Query query = Query.builder().setItem(selector).setOperator(NOT_IN).setValue(arguments).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #29
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testVisitComparisonNodeIn() {
  String selector = "name";
  List<String> arguments = asList("jan", "piet");
  ComparisonOperator operator = new ComparisonOperator("=in=", true);
  ComparisonNode node = new ComparisonNode(operator, selector, arguments);

  Query query = Query.builder().setItem(selector).setOperator(IN).setValue(arguments).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}
 
Example #30
Source File: QueryRsqlVisitorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("testVisitComparisonNodeGreaterThanProvider")
void testVisitComparisonNodeGreaterThan(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).setValue(argument).build();
  assertEquals(query, queryRsqlVisitor.visit(node));
}