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

The following examples show how to use cz.jirutka.rsql.parser.ast.Node. 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
@Override
public Query convert(@Nonnull String source) {
  Node node;
  try {
    node = rsqlParser.parse(source);
  } catch (RSQLParserException e) {
    Throwable cause = e.getCause();
    if (cause instanceof UnknownOperatorException) {
      String operator = ((UnknownOperatorException) cause).getOperator();
      throw new UnknownQueryOperatorException(operator);
    } else {
      throw new QueryParseException(e);
    }
  }
  return node.accept(rsqlVisitor);
}
 
Example 3
@Override
public Query<Entity> visit(AndNode node) {
  initQuery();
  boolean nested = node.getChildren().size() > 1;
  if (nested) {
    q.nest();
  }
  for (Iterator<Node> it = node.iterator(); it.hasNext(); ) {
    Node child = it.next();
    child.accept(this);

    if (it.hasNext()) {
      q.and();
    }
  }
  if (nested) {
    q.unnest();
  }
  return q;
}
 
Example 4
@Override
public Query<Entity> visit(OrNode node) {
  initQuery();
  boolean nested = node.getChildren().size() > 1;
  if (nested) {
    q.nest();
  }

  for (Iterator<Node> it = node.iterator(); it.hasNext(); ) {
    Node child = it.next();
    child.accept(this);

    if (it.hasNext()) {
      q.or();
    }
  }
  if (nested) {
    q.unnest();
  }

  return q;
}
 
Example 5
Source Project: gemini   Source File: PersistenceEntityManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void addFilter(QueryWithParams query, FilterContext filterContext, Entity entity) {
    FilterContext.FilterType filterType = filterContext.getFilterType();
    if (filterType == FilterContext.FilterType.GEMINI && !filterContext.getSearchString().isEmpty()) {
        Node rootNode = new RSQLParser(filterVisitor.getOperators()).parse(filterContext.getSearchString());

        QueryWithParams queryWithParams = rootNode.accept(filterVisitor, FilterVisitor.FilterVisitorContext.of(entity));
        query.addToSql(" WHERE " + queryWithParams.getSql());
        query.addParams(queryWithParams.getParams());
    }
    if (filterType == FilterContext.FilterType.PERSISTENCE) {
        query.addToSql(" WHERE " + filterContext.getSearchString());
        query.addParams(filterContext.getParams());
    }
}
 
Example 6
Source Project: rsql-jpa-specification   Source File: RSQLJPASupport.java    License: MIT License 5 votes vote down vote up
public static <T> Specification<T> toSpecification(final String rsqlQuery, final boolean distinct, final Map<String, String> propertyPathMapper) {
	log.debug("toSpecification({},distinct:{},propertyPathMapper:{})", rsqlQuery, distinct, propertyPathMapper);
	return new Specification<T>() {
		public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			query.distinct(distinct);
			if (StringUtils.hasText(rsqlQuery)) {
				Node rsql = new RSQLParser(RSQLOperators.supportedOperators()).parse(rsqlQuery);
				return rsql.accept(new RSQLJPAPredicateConverter(cb, propertyPathMapper), root);
			} else
				return null;
		}
	};
}
 
Example 7
Source Project: dremio-oss   Source File: SearchFilterToQueryConverter.java    License: Apache License 2.0 5 votes vote down vote up
public static SearchQuery toQuery(String filterStr, FilterIndexMapping mapping){

    if(Strings.isNullOrEmpty(filterStr)){
      return SearchQueryUtils.newMatchAllQuery();
    }

    final Node root = new RSQLParser(RSQL_OPERATORS).parse(filterStr);
    return root.accept(new SearchFilterToQueryConverter(mapping).visitor);
  }
 
Example 8
Source Project: dremio-oss   Source File: SearchFilterToQueryConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SearchQuery visit(final AndNode node) {
  final List<SearchQuery> queries = new ArrayList<>();
  for (final Node child: node.getChildren()) {
    queries.add(child.accept(this));
  }
  return SearchQueryUtils.and(queries);
}
 
Example 9
Source Project: dremio-oss   Source File: SearchFilterToQueryConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SearchQuery visit(final OrNode node) {
  final List<SearchQuery> queries = new ArrayList<>();
  for (final Node child: node.getChildren()) {
    queries.add(child.accept(this));
  }
  return SearchQueryUtils.or(queries);
}
 
Example 10
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Predicate toPredicate(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Node rootNode = parseRsql(rsql);
    query.distinct(true);

    final JpqQueryRSQLVisitor<A, T> jpqQueryRSQLVisitor = new JpqQueryRSQLVisitor<>(root, cb, enumType,
            virtualPropertyReplacer, database, query);
    final List<Predicate> accept = rootNode.<List<Predicate>, String> accept(jpqQueryRSQLVisitor);

    if (!CollectionUtils.isEmpty(accept)) {
        return cb.and(accept.toArray(new Predicate[accept.size()]));
    }
    return cb.conjunction();

}
 
Example 11
Source Project: hawkbit   Source File: RSQLUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private List<Predicate> acceptChilds(final LogicalNode node) {
    final List<Node> children = node.getChildren();
    final List<Predicate> childs = new ArrayList<>();
    for (final Node node2 : children) {
        final List<Predicate> accept = node2.accept(this);
        if (!CollectionUtils.isEmpty(accept)) {
            childs.addAll(accept);
        } else {
            LOGGER.debug("visit logical node children but could not parse it, ignoring {}", node2);
        }
    }
    return childs;
}
 
Example 12
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 13
Source Project: pnc   Source File: RSQLProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <DB extends GenericEntity<?>> Predicate<DB> getCriteriaPredicate(Class<DB> type, String rsql) {
    if (rsql == null || rsql.isEmpty()) {
        return new EmptyRSQLPredicate();
    }
    Node rootNode = predicateParser.parse(preprocessRSQL(rsql));
    return getEntityPredicate(rootNode, type);
}
 
Example 14
Source Project: pnc   Source File: RSQLProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> java.util.function.Predicate<T> getStreamPredicate(String rsql) {
    if (rsql == null || rsql.isEmpty()) {
        return x -> true;
    }
    Node rootNode = predicateParser.parse(preprocessRSQL(rsql));
    return getStreamPredicate(rootNode);
}
 
Example 15
Source Project: pnc   Source File: RSQLProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <DB extends GenericEntity<?>> SortInfo getSortInfo(Class<DB> type, String rsql) {
    if (rsql == null || rsql.isEmpty()) {
        return new EmptySortInfo();
    }

    if (!rsql.startsWith(FIXED_START_OF_SORTING_EXPRESSION)) {
        rsql = FIXED_START_OF_SORTING_EXPRESSION + rsql;
    }

    Node rootNode = sortParser.parse(preprocessRSQL(rsql));
    Function<RSQLSelectorPath, String> toPath = (RSQLSelectorPath selector) -> mapper.toPath(type, selector);
    return (SortInfo) rootNode.accept(new SortRSQLNodeTraveller(toPath));
}
 
Example 16
Source Project: pnc   Source File: RSQLProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <DTO> Comparator<DTO> getComparator(String rsql) {
    if (rsql == null || rsql.isEmpty()) {
        throw new RSQLException("RSQL sort query must be non-empty and non-null.");
    }
    if (!rsql.startsWith(FIXED_START_OF_SORTING_EXPRESSION)) {
        rsql = FIXED_START_OF_SORTING_EXPRESSION + rsql;
    }
    Node rootNode = sortParser.parse(preprocessRSQL(rsql));

    return rootNode.accept(new ComparatorRSQLNodeTraveller<>());
}
 
Example 17
Source Project: pnc   Source File: RSQLProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private <DB extends GenericEntity<?>> Predicate<DB> getEntityPredicate(Node rootNode, Class<DB> type) {
    return (root, query, cb) -> {
        RSQLNodeTraveller<javax.persistence.criteria.Predicate> visitor = new EntityRSQLNodeTraveller(
                root,
                cb,
                new BiFunction<From<?, DB>, RSQLSelectorPath, Path>() {
                    @Override
                    public Path apply(From<?, DB> from, RSQLSelectorPath selector) {
                        return mapper.toPath(type, from, selector);
                    }
                });
        return rootNode.accept(visitor);
    };
}
 
Example 18
Source Project: pnc   Source File: RSQLProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private <T> java.util.function.Predicate<T> getStreamPredicate(Node rootNode) {
    return instance -> {
        RSQLNodeTraveller<Boolean> visitor = new StreamRSQLNodeTraveller(instance);

        return rootNode.accept(visitor);
    };
}
 
Example 19
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 20
private Set<Sid> getSidsFromQuery(String queryString) {
  Set<Sid> sids = Collections.emptySet();
  if (!Strings.isNullOrEmpty(queryString)) {
    try {
      Node node = rsqlParser.parse(queryString);
      PermissionsQuery permissionsQuery = node.accept(new PermissionRsqlVisitor());
      sids =
          new LinkedHashSet<>(
              userRoleTools.getSids(permissionsQuery.getUsers(), permissionsQuery.getRoles()));
    } catch (RSQLParserException e) {
      throw new PermissionQueryParseException(e);
    }
  }
  return sids;
}
 
Example 21
@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 22
@Override
public AggregateQuery visit(AndNode node) {
  for (Node child : node) {
    child.accept(this);
  }

  return aggsQ;
}
 
Example 23
Source Project: tutorials   Source File: UserController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
@ResponseBody
public List<User> findAllByRsql(@RequestParam(value = "search") String search) {
    Node rootNode = new RSQLParser().parse(search);
    Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
    return dao.findAll(spec);
}
 
Example 24
Source Project: tutorials   Source File: GenericRsqlSpecBuilder.java    License: MIT License 5 votes vote down vote up
public Specification<T> createSpecification(final Node node) {
    if (node instanceof LogicalNode) {
        return createSpecification((LogicalNode) node);
    }
    if (node instanceof ComparisonNode) {
        return createSpecification((ComparisonNode) node);
    }
    return null;
}
 
Example 25
Source Project: tutorials   Source File: RsqlIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
    final Node rootNode = new RSQLParser().parse("firstName==john;lastName==doe");
    final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
    final List<User> results = repository.findAll(spec);

    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}
 
Example 26
Source Project: tutorials   Source File: RsqlIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() {
    final Node rootNode = new RSQLParser().parse("firstName!=john");
    final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
    final List<User> results = repository.findAll(spec);

    assertThat(userTom, isIn(results));
    assertThat(userJohn, not(isIn(results)));
}
 
Example 27
Source Project: tutorials   Source File: RsqlIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenMinAge_whenGettingListOfUsers_thenCorrect() {
    final Node rootNode = new RSQLParser().parse("age>25");
    final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
    final List<User> results = repository.findAll(spec);

    assertThat(userTom, isIn(results));
    assertThat(userJohn, not(isIn(results)));
}
 
Example 28
Source Project: tutorials   Source File: RsqlIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() {
    final Node rootNode = new RSQLParser().parse("firstName==jo*");
    final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
    final List<User> results = repository.findAll(spec);

    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}
 
Example 29
Source Project: tutorials   Source File: RsqlIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenListOfFirstName_whenGettingListOfUsers_thenCorrect() {
    final Node rootNode = new RSQLParser().parse("firstName=in=(john,jack)");
    final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
    final List<User> results = repository.findAll(spec);

    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}
 
Example 30
@Test
void testVisitAnd() {
  Node node = mock(Node.class);
  AndNode andNode = new AndNode(Arrays.asList(node, node));
  assertThrows(UnsupportedPermissionQueryOperatorException.class, () -> visitor.visit(andNode));
}