rest-query-engine icon indicating copy to clipboard operation
rest-query-engine copied to clipboard

Error when search for an element in null Collection/Array

Open FHamster opened this issue 3 years ago • 0 comments

This error occurs when predicatevisitor is used as the visitor of AST

Predicate<Element> predicate = condition.query(new PredicateVisitor<>());

I have a collection like this

[
  {
    "_id": "604da82b13b1687602fd97e5",
    "author": [
      {
        "_VALUE": "Frank Piessens"
      }
    ]
  },
  {
    "_id": "604da89613b1687602141823",
    "author": null
  }
]    

The RSQL query will process

author._VALUE=="Frank Piessens"

Then the error happended.The log is very simple.

java.lang.NullPointerException: null
	at com.github.rutledgepaulv.qbuilders.visitors.PredicateVisitor.recurseSingle(PredicateVisitor.java:232) ~[q-builders-1.5.jar:na]
	...

I found out that the code in PredicateVisitor.recurseSingle isn't null safe.The if statement will throw a exception,when parameter root is null.So I override the method PredicateVisitor.recurseSingle in q-builder https://github.com/RutledgePaulV/q-builders/blob/develop/src/main/java/com/github/rutledgepaulv/qbuilders/visitors/PredicateVisitor.java

private boolean recurseSingle(Object root, String field, ComparisonNode node, BiPredicate<Object, Object> func) {
  			//Add an if statement
  			//Ensure null safe
        if (root == null) {
            return Stream.empty().anyMatch(t -> resolveSingleField(t, field, node, func));
        }
        if (root.getClass().isArray()) {
            return Arrays.stream((Object[]) root).anyMatch(t -> resolveSingleField(t, field, node, func));
        }

        if (root instanceof Collection) {
            return ((Collection<Object>) root).stream().anyMatch(t -> resolveSingleField(t, field, node, func));
        }

        return resolveSingleField(root, field, node, func);
    }

Hope to help others.

FHamster avatar Mar 15 '21 15:03 FHamster