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

The following examples show how to use cz.jirutka.rsql.parser.ast.Node. 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: 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 #2
Source File: MolgenisRSQLVisitor.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #3
Source File: MolgenisRSQLVisitor.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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
Source File: QueryConverter.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: RsqlIntegrationTest.java    From tutorials with 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 #6
Source File: PersistenceEntityManagerImpl.java    From gemini with 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 #7
Source File: RsqlIntegrationTest.java    From tutorials with 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 #8
Source File: RsqlIntegrationTest.java    From tutorials with 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 #9
Source File: RsqlIntegrationTest.java    From tutorials with 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 #10
Source File: RsqlIntegrationTest.java    From tutorials with 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 #11
Source File: GenericRsqlSpecBuilder.java    From tutorials with 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 #12
Source File: UserController.java    From tutorials with 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 #13
Source File: AggregateQueryRsqlVisitor.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public AggregateQuery visit(AndNode node) {
  for (Node child : node) {
    child.accept(this);
  }

  return aggsQ;
}
 
Example #14
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 #15
Source File: PermissionsController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #16
Source File: RSQLProducerImpl.java    From pnc with 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 #17
Source File: RSQLJPASupport.java    From rsql-jpa-specification with 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 #18
Source File: SearchFilterToQueryConverter.java    From dremio-oss with 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 #19
Source File: SearchFilterToQueryConverter.java    From dremio-oss with 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 #20
Source File: SearchFilterToQueryConverter.java    From dremio-oss with 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 #21
Source File: RSQLUtility.java    From hawkbit with 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 #22
Source File: RSQLUtility.java    From hawkbit with 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 #23
Source File: RSQLNodeTraveller.java    From pnc with 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 #24
Source File: RSQLProducerImpl.java    From pnc with 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 #25
Source File: RSQLProducerImpl.java    From pnc with 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 #26
Source File: RSQLProducerImpl.java    From pnc with 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 #27
Source File: RSQLProducerImpl.java    From pnc with 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 #28
Source File: RSQLProducerImpl.java    From pnc with 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 #29
Source File: RSQLNodeTraveller.java    From pnc with 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 #30
Source File: AggregateQueryRsqlConverter.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public AggregateQueryRsql convert(String source) {
  Node rootNode = rsqlParser.parse(source);
  return new AggregateQueryRsql(rootNode);
}