Browse Source

Parent references

pull/1/head
U-SWNA\dbaldwin100 14 years ago
parent
commit
6fe9525d4e
  1. 28
      json-path-assert/src/main/java/com/jayway/jsonassert/JsonAssert.java
  2. 21
      json-path-assert/src/main/java/com/jayway/jsonassert/JsonAsserter.java
  3. 33
      json-path-assert/src/main/java/com/jayway/jsonassert/impl/JsonAsserterImpl.java
  4. 66
      json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java
  5. 34
      json-path/pom.xml
  6. 48
      json-path/src/main/java/com/jayway/jsonpath/InvalidPathException.java
  7. 392
      json-path/src/main/java/com/jayway/jsonpath/JsonPath.java
  8. 142
      json-path/src/main/java/com/jayway/jsonpath/PathUtil.java
  9. 176
      json-path/src/main/java/com/jayway/jsonpath/eval/ExpressionEvaluator.java
  10. 105
      json-path/src/main/java/com/jayway/jsonpath/filter/FilterOutput.java
  11. 41
      json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterBase.java
  12. 109
      json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterChain.java
  13. 80
      json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterFactory.java
  14. 164
      json-path/src/main/java/com/jayway/jsonpath/filter/ListEvalFilter.java
  15. 148
      json-path/src/main/java/com/jayway/jsonpath/filter/ListFrontFilter.java
  16. 150
      json-path/src/main/java/com/jayway/jsonpath/filter/ListIndexFilter.java
  17. 114
      json-path/src/main/java/com/jayway/jsonpath/filter/ListPropertyFilter.java
  18. 125
      json-path/src/main/java/com/jayway/jsonpath/filter/ListTailFilter.java
  19. 55
      json-path/src/main/java/com/jayway/jsonpath/filter/ListWildcardFilter.java
  20. 113
      json-path/src/main/java/com/jayway/jsonpath/filter/PropertyFilter.java
  21. 52
      json-path/src/main/java/com/jayway/jsonpath/filter/RootFilter.java
  22. 103
      json-path/src/main/java/com/jayway/jsonpath/filter/TraverseFilter.java
  23. 87
      json-path/src/main/java/com/jayway/jsonpath/filter/WildcardPropertyFilter.java
  24. 130
      json-path/src/test/java/com/jayway/jsonpath/ExpressionEvalTest.java
  25. 491
      json-path/src/test/java/com/jayway/jsonpath/JsonPathTest.java
  26. 26
      json-path/src/test/java/com/jayway/jsonpath/ParserTest.java
  27. 60
      json-path/src/test/java/com/jayway/jsonpath/PathUtilTest.java
  28. 138
      json-path/src/test/java/com/jayway/jsonpath/SplitPathFragmentsTest.java

28
json-path-assert/src/main/java/com/jayway/jsonassert/JsonAssert.java

@ -3,8 +3,11 @@ package com.jayway.jsonassert;
import com.jayway.jsonassert.impl.JsonAsserterImpl; import com.jayway.jsonassert.impl.JsonAsserterImpl;
import com.jayway.jsonassert.impl.matcher.*; import com.jayway.jsonassert.impl.matcher.*;
import com.jayway.jsonpath.json.JsonFactory;
import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.JSONParser;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.core.IsNull;
import java.io.*; import java.io.*;
import java.text.ParseException; import java.text.ParseException;
@ -18,7 +21,7 @@ import java.util.Map;
*/ */
public class JsonAssert { public class JsonAssert {
private static JSONParser JSON_PARSER = new JSONParser(); private static JsonFactory JSON_PARSER = JsonFactory.getInstance();
public final static int STRICT_MODE = 0; public final static int STRICT_MODE = 0;
public final static int SLACK_MODE = -1; public final static int SLACK_MODE = -1;
@ -28,7 +31,7 @@ public class JsonAssert {
public static void setMode(int mode) { public static void setMode(int mode) {
if (mode != JsonAssert.mode) { if (mode != JsonAssert.mode) {
JsonAssert.mode = mode; JsonAssert.mode = mode;
JSON_PARSER = new JSONParser(JsonAssert.mode);
} }
} }
@ -42,12 +45,12 @@ public class JsonAssert {
* @param json the JSON document to create a JSONAsserter for * @param json the JSON document to create a JSONAsserter for
* @return a JSON asserter initialized with the provided document * @return a JSON asserter initialized with the provided document
* @throws ParseException when the given JSON could not be parsed * @throws ParseException when the given JSON could not be parsed
* @throws com.jayway.jsonpath.json.ParseException
* @throws com.jayway.jsonpath.json.ParseException
*/ */
public static JsonAsserter with(String json) throws ParseException { public static JsonAsserter with(String json) throws com.jayway.jsonpath.json.ParseException {
try { try {
return new JsonAsserterImpl(JSON_PARSER.parse(json)); return new JsonAsserterImpl(JSON_PARSER.parse(json));
} catch (net.minidev.json.parser.ParseException e) {
throw new ParseException(json, e.getPosition());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -59,13 +62,12 @@ public class JsonAssert {
* @param reader the reader of the json document * @param reader the reader of the json document
* @return a JSON asserter initialized with the provided document * @return a JSON asserter initialized with the provided document
* @throws ParseException when the given JSON could not be parsed * @throws ParseException when the given JSON could not be parsed
* @throws com.jayway.jsonpath.json.ParseException
*/ */
public static JsonAsserter with(Reader reader) throws ParseException, IOException { public static JsonAsserter with(Reader reader) throws ParseException, IOException, com.jayway.jsonpath.json.ParseException {
try {
return new JsonAsserterImpl(JSON_PARSER.parse(convertReaderToString(reader))); return new JsonAsserterImpl(JSON_PARSER.parse(convertReaderToString(reader)));
} catch (net.minidev.json.parser.ParseException e) {
throw new ParseException(e.toString(), e.getPosition());
}
} }
/** /**
@ -74,8 +76,9 @@ public class JsonAssert {
* @param is the input stream * @param is the input stream
* @return a JSON asserter initialized with the provided document * @return a JSON asserter initialized with the provided document
* @throws ParseException when the given JSON could not be parsed * @throws ParseException when the given JSON could not be parsed
* @throws com.jayway.jsonpath.json.ParseException
*/ */
public static JsonAsserter with(InputStream is) throws ParseException, IOException { public static JsonAsserter with(InputStream is) throws ParseException, IOException, com.jayway.jsonpath.json.ParseException {
Reader reader = new InputStreamReader(is); Reader reader = new InputStreamReader(is);
return with(reader); return with(reader);
} }
@ -97,6 +100,9 @@ public class JsonAssert {
public static Matcher<Collection<Object>> emptyCollection() { public static Matcher<Collection<Object>> emptyCollection() {
return new IsEmptyCollection<Object>(); return new IsEmptyCollection<Object>();
} }
public static Matcher<Object> isnull() {
return new IsNull<Object>();
}
private static String convertReaderToString(Reader reader) private static String convertReaderToString(Reader reader)
throws IOException { throws IOException {

21
json-path-assert/src/main/java/com/jayway/jsonassert/JsonAsserter.java

@ -2,6 +2,8 @@ package com.jayway.jsonassert;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import com.jayway.jsonpath.json.JsonException;
/** /**
* User: kallestenflo * User: kallestenflo
* Date: 1/24/11 * Date: 1/24/11
@ -23,8 +25,10 @@ public interface JsonAsserter {
* @param matcher an expression, built of Matchers, specifying allowed values * @param matcher an expression, built of Matchers, specifying allowed values
* @param <T> the static type accepted by the matcher * @param <T> the static type accepted by the matcher
* @return this to allow fluent assertion chains * @return this to allow fluent assertion chains
* @throws AssertionError
* @throws JsonException
*/ */
<T> JsonAsserter assertThat(String path, Matcher<T> matcher); <T> JsonAsserter assertThat(String path, Matcher<T> matcher) throws JsonException, AssertionError;
/** /**
* Asserts that object specified by path is equal to the expected value. * Asserts that object specified by path is equal to the expected value.
@ -34,8 +38,10 @@ public interface JsonAsserter {
* @param expected the expected value * @param expected the expected value
* @param <T> the static type that should be returned by the path * @param <T> the static type that should be returned by the path
* @return this to allow fluent assertion chains * @return this to allow fluent assertion chains
* @throws AssertionError
* @throws JsonException
*/ */
<T> JsonAsserter assertEquals(String path, T expected); <T> JsonAsserter assertEquals(String path, T expected) throws JsonException, AssertionError;
/** /**
* Checks that a path is not defined within a document. If the document contains the * Checks that a path is not defined within a document. If the document contains the
@ -43,8 +49,9 @@ public interface JsonAsserter {
* *
* @param path the path to make sure not exists * @param path the path to make sure not exists
* @return this * @return this
* @throws JsonException
*/ */
JsonAsserter assertNotDefined(String path); JsonAsserter assertNotDefined(String path) throws JsonException;
/** /**
@ -53,8 +60,10 @@ public interface JsonAsserter {
* *
* @param path the json path specifying the value that should be null * @param path the json path specifying the value that should be null
* @return this to allow fluent assertion chains * @return this to allow fluent assertion chains
* @throws AssertionError
* @throws JsonException
*/ */
JsonAsserter assertNull(String path); JsonAsserter assertNull(String path) throws JsonException, AssertionError;
/** /**
* Asserts that object specified by path is NOT null. If it is, an AssertionError * Asserts that object specified by path is NOT null. If it is, an AssertionError
@ -62,8 +71,10 @@ public interface JsonAsserter {
* *
* @param path the json path specifying the value that should be NOT null * @param path the json path specifying the value that should be NOT null
* @return this to allow fluent assertion chains * @return this to allow fluent assertion chains
* @throws AssertionError
* @throws JsonException
*/ */
<T> JsonAsserter assertNotNull(String path); <T> JsonAsserter assertNotNull(String path) throws JsonException, AssertionError;
/** /**
* Syntactic sugar to allow chaining assertions with a separating and() statement * Syntactic sugar to allow chaining assertions with a separating and() statement

33
json-path-assert/src/main/java/com/jayway/jsonassert/impl/JsonAsserterImpl.java

@ -3,6 +3,9 @@ package com.jayway.jsonassert.impl;
import com.jayway.jsonassert.JsonAsserter; import com.jayway.jsonassert.JsonAsserter;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.json.JsonElement;
import com.jayway.jsonpath.json.JsonException;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import static java.lang.String.format; import static java.lang.String.format;
@ -16,7 +19,7 @@ import static org.hamcrest.Matchers.*;
public class JsonAsserterImpl implements JsonAsserter { public class JsonAsserterImpl implements JsonAsserter {
private final Object jsonObject; private final JsonElement jsonObject;
/** /**
@ -24,20 +27,23 @@ public class JsonAsserterImpl implements JsonAsserter {
* *
* @param jsonObject the object to make asserts on * @param jsonObject the object to make asserts on
*/ */
public JsonAsserterImpl(Object jsonObject) { public JsonAsserterImpl(JsonElement jsonObject) {
this.jsonObject = jsonObject; this.jsonObject = jsonObject;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* @throws AssertionError
* @throws JsonException
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> JsonAsserter assertThat(String path, Matcher<T> matcher) { public <T> JsonAsserter assertThat(String path, Matcher<T> matcher) throws JsonException, AssertionError {
String reason = "When processing json path: " + path; String reason = "When processing json path: " + path;
if (!matcher.matches(JsonPath.<T>read(jsonObject, path))) { JsonElement je = JsonPath.read(jsonObject, path);
if (!( (je == null && matcher.matches(je)) || (je.isContainer() && matcher.matches(je)) || matcher.matches(je.toObject()) ) ) {
System.out.println(JsonPath.read(jsonObject, path).toString()); System.out.println(JsonPath.read(jsonObject, path).toString());
@ -61,18 +67,21 @@ public class JsonAsserterImpl implements JsonAsserter {
/** /**
* {@inheritDoc} * {@inheritDoc}
* @throws AssertionError
* @throws JsonException
*/ */
public <T> JsonAsserter assertEquals(String path, T expected) { public <T> JsonAsserter assertEquals(String path, T expected) throws JsonException, AssertionError {
return assertThat(path, equalTo(expected)); return assertThat(path, equalTo(expected));
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* @throws JsonException
*/ */
public JsonAsserter assertNotDefined(String path) { public JsonAsserter assertNotDefined(String path) throws JsonException {
Object o = JsonPath.read(jsonObject, path); JsonElement o = JsonPath.read(jsonObject, path);
if (o != null) { if (!o.isJsonNull()) {
throw new AssertionError(format("Document contains the path <%s> but was expected not to.", path)); throw new AssertionError(format("Document contains the path <%s> but was expected not to.", path));
} }
return this; return this;
@ -80,15 +89,19 @@ public class JsonAsserterImpl implements JsonAsserter {
/** /**
* {@inheritDoc} * {@inheritDoc}
* @throws AssertionError
* @throws JsonException
*/ */
public JsonAsserter assertNull(String path) { public JsonAsserter assertNull(String path) throws JsonException, AssertionError {
return assertThat(path, nullValue()); return assertThat(path, nullValue());
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* @throws AssertionError
* @throws JsonException
*/ */
public <T> JsonAsserter assertNotNull(String path) { public <T> JsonAsserter assertNotNull(String path) throws JsonException, AssertionError {
return assertThat(path, notNullValue()); return assertThat(path, notNullValue());
} }

66
json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java

@ -1,8 +1,15 @@
package com.jayway.jsonassert; package com.jayway.jsonassert;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import com.jayway.jsonpath.json.JsonElement;
import com.jayway.jsonpath.json.JsonException;
import com.jayway.jsonpath.json.JsonFactory;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -14,7 +21,7 @@ import static org.hamcrest.Matchers.*;
* Date: 1/21/11 * Date: 1/21/11
* Time: 4:04 PM * Time: 4:04 PM
*/ */
public class JsonAssertTest { public abstract class JsonAssertTest {
public final static String JSON = public final static String JSON =
"{ \"store\": {\n" + "{ \"store\": {\n" +
@ -49,8 +56,17 @@ public class JsonAssertTest {
" }\n" + " }\n" +
" }\n" + " }\n" +
"}"; "}";
protected JsonFactory factory = null;
@Before
public void init(){
init_factory();
}
protected void init_factory(){
}
@Test @Test
public void links_document() throws Exception { public void links_document() throws Exception {
@ -88,42 +104,56 @@ public class JsonAssertTest {
@Test @Test
public void list_content_can_be_asserted_with_matcher() throws Exception { public void list_content_can_be_asserted_with_matcher() throws Exception {
with(JSON).assertThat("$..book[*].author", hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); with(JSON).assertThat("$..book[*].author", hasItems( factory.createJsonPrimitive("Nigel Rees"), factory.createJsonPrimitive("Evelyn Waugh"), factory.createJsonPrimitive("Herman Melville"),factory.createJsonPrimitive( "J. R. R. Tolkien")));
with(JSON).assertThat("$..author", hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")) with(JSON).assertThat("$..author.(value)", hasItems( factory.createJsonPrimitive("Nigel Rees"), factory.createJsonPrimitive("Evelyn Waugh"), factory.createJsonPrimitive("Herman Melville"),factory.createJsonPrimitive( "J. R. R. Tolkien")))
.assertThat("$..author", is(collectionWithSize(equalTo(4)))); .assertThat("$..author.(value)", is(collectionWithSize(equalTo(4))));
} }
@Test @Test
public void list_content_can_be_asserted_with_nested_matcher() throws Exception { public void list_content_can_be_asserted_with_nested_matcher() throws Exception {
with(JSON).assertThat("$..book[*]", hasItems(hasEntry("author", "Nigel Rees"), hasEntry("author", "Evelyn Waugh"))); with(JSON).assertThat("$..book[*]", hasItems(hasEntry("author", factory.createJsonPrimitive("Nigel Rees")), hasEntry("author", factory.createJsonPrimitive("Evelyn Waugh"))));
} }
@Test @Test
public void map_content_can_be_asserted_with_matcher() throws Exception { public void map_content_can_be_asserted_with_matcher() throws Exception {
with(JSON).assertThat("$.store.book[0]", hasEntry("category", "reference")) with(JSON).assertThat("$.store.book[0]", hasEntry("category", w("reference")))
.assertThat("$.store.book[0]", hasEntry("title", "Sayings of the Century")) .assertThat("$.store.book[0]", hasEntry("title", w("Sayings of the Century")))
.and() .and()
.assertThat("$..book[0]", hasEntry("category", "reference")) .assertThat("$..book[0]", hasEntry("category", w("reference")))
.and() .and()
.assertThat("$.store.book[0]", mapContainingKey(equalTo("category"))) .assertThat("$.store.book[0]", mapContainingKey(equalTo("category")))
.and() .and()
.assertThat("$.store.book[0]", mapContainingValue(equalTo("reference"))); .assertThat("$.store.book[0]", mapContainingValue(equalTo( w("reference"))));
with(JSON).assertThat("$.['store'].['book'][0]", hasEntry("category", "reference")) with(JSON).assertThat("$.['store'].['book'][0]", hasEntry(w("category"), w("reference")))
.assertThat("$.['store'].['book'][0]", hasEntry("title", "Sayings of the Century")) .assertThat("$.['store'].['book'][0]", hasEntry("title", w("Sayings of the Century")))
.and() .and()
.assertThat("$..['book'][0]", hasEntry("category", "reference")) .assertThat("$..['book'][0]", hasEntry(w("category"), w("reference")))
.and() .and()
.assertThat("$.['store'].['book'][0]", mapContainingKey(equalTo("category"))) .assertThat("$.['store'].['book'][0]", mapContainingKey(equalTo(("category"))))
.and() .and()
.assertThat("$.['store'].['book'][0]", mapContainingValue(equalTo("reference"))); .assertThat("$.['store'].['book'][0]", mapContainingValue(equalTo(w("reference"))));
} }
@Test
private JsonElement w(Object obj) throws JsonException {
return factory.createJsonPrimitive(obj);
}
private JsonElement[] w(Object ... objs) throws JsonException {
JsonElement je[]= new JsonElement[objs.length];
for(int i=0;i<objs.length;i++){
je[i] = w(objs[i]);
}
return je;
}
@Test
public void an_empty_collection() throws Exception { public void an_empty_collection() throws Exception {
with(JSON).assertThat("$.store.book[?(@.category = 'x')]", emptyCollection()); with(JSON).assertThat("$.store.book[?(@.category = 'x')]", isnull());
} }
@Test @Test
@ -140,12 +170,12 @@ public class JsonAssertTest {
@Test @Test
public void invalid_path() throws Exception { public void invalid_path() throws Exception {
with(JSON).assertThat("$.store.book[*].fooBar", emptyCollection()); with(JSON).assertThat("$.store.book[*].fooBar.(value)", Matchers.<Object>nullValue());
} }
@Test @Test
public void path_including_wildcard_path_followed_by_another_path_concatenates_results_to_list() throws Exception { public void path_including_wildcard_path_followed_by_another_path_concatenates_results_to_list() throws Exception {
with(getResourceAsStream("lotto.json")).assertThat("lotto.winners[*].winnerId", hasItems(23, 54)); with(getResourceAsStream("lotto.json")).assertThat("lotto.winners[*].winnerId", hasItems( factory.createJsonPrimitive(23), factory.createJsonPrimitive(54)));
} }

34
json-path/pom.xml

@ -17,8 +17,8 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-parent</artifactId> <artifactId>json-path-parent</artifactId>
<groupId>com.jayway.jsonpath</groupId>
<version>0.5.5-SNAPSHOT</version> <version>0.5.5-SNAPSHOT</version>
</parent> </parent>
<groupId>com.jayway.jsonpath</groupId> <groupId>com.jayway.jsonpath</groupId>
@ -44,13 +44,43 @@
<artifactId>commons-lang</artifactId> <artifactId>commons-lang</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.6</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>net.minidev</groupId> <groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId> <artifactId>json-smart</artifactId>
<version>1.0.6.3</version> <version>1.0.6.3</version>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.11</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.11</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.11</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- test dependencies --> <!-- test dependencies -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->

48
json-path/src/main/java/com/jayway/jsonpath/InvalidPathException.java

@ -1,24 +1,24 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
/** /**
* User: kalle stenflo * User: kalle stenflo
* Date: 1/24/11 * Date: 1/24/11
* Time: 10:09 AM * Time: 10:09 AM
*/ */
public class InvalidPathException extends RuntimeException { public class InvalidPathException extends RuntimeException {
public InvalidPathException() { public InvalidPathException() {
} }
public InvalidPathException(String message) { public InvalidPathException(String message) {
super(message); super(message);
} }
public InvalidPathException(String message, Throwable cause) { public InvalidPathException(String message, Throwable cause) {
super(message, cause); super(message, cause);
} }
public InvalidPathException(Throwable cause) { public InvalidPathException(Throwable cause) {
super(cause); super(cause);
} }
} }

392
json-path/src/main/java/com/jayway/jsonpath/JsonPath.java

@ -1,189 +1,203 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import com.jayway.jsonpath.filter.FilterOutput; import com.jayway.jsonpath.filter.FilterOutput;
import com.jayway.jsonpath.filter.JsonPathFilterChain; import com.jayway.jsonpath.filter.JsonPathFilterChain;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonElement;
import net.minidev.json.JSONObject; import com.jayway.jsonpath.json.JsonException;
import net.minidev.json.parser.JSONParser; import com.jayway.jsonpath.json.JsonFactory;
import net.minidev.json.parser.ParseException; import com.jayway.jsonpath.json.JsonParser;
import java.io.IOException;
import java.util.logging.Logger;
import java.io.IOException;
/** import java.util.logging.Logger;
* User: kalle stenflo
* Date: 2/2/11 import net.minidev.json.parser.ParseException;
* Time: 1:03 PM
* <p/>
* JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is /**
* available in many programming languages such as Javascript, Python and PHP. * User: kalle stenflo
* <p/> * Date: 2/2/11
* JsonPath allows you to compile a json path string to use it many times or to compile and apply in one * Time: 1:03 PM
* single on demand operation. * <p/>
* <p/> * JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is
* Given the Json document: * available in many programming languages such as Javascript, Python and PHP.
* <p/> * <p/>
* <code> * JsonPath allows you to compile a json path string to use it many times or to compile and apply in one
* String json = * single on demand operation.
* "{ * <p/>
* "store": * Given the Json document:
* { * <p/>
* "book": * <code>
* [ * String json =
* { * "{
* "category": "reference", * "store":
* "author": "Nigel Rees", * {
* "title": "Sayings of the Century", * "book":
* "price": 8.95 * [
* }, * {
* { * "category": "reference",
* "category": "fiction", * "author": "Nigel Rees",
* "author": "Evelyn Waugh", * "title": "Sayings of the Century",
* "title": "Sword of Honour", * "price": 8.95
* "price": 12.99 * },
* } * {
* ], * "category": "fiction",
* "bicycle": * "author": "Evelyn Waugh",
* { * "title": "Sword of Honour",
* "color": "red", * "price": 12.99
* "price": 19.95 * }
* } * ],
* } * "bicycle":
* }"; * {
* </code> * "color": "red",
* <p/> * "price": 19.95
* A JsonPath can be compiled and used as shown: * }
* <p/> * }
* <code> * }";
* JsonPath path = JsonPath.compile("$.store.book[1]"); * </code>
* <br/> * <p/>
* List&lt;Object&gt; books = path.read(json); * A JsonPath can be compiled and used as shown:
* </code> * <p/>
* </p> * <code>
* Or: * JsonPath path = JsonPath.compile("$.store.book[1]");
* <p/> * <br/>
* <code> * List&lt;Object&gt; books = path.read(json);
* List&lt;Object&gt; authors = JsonPath.read(json, "$.store.book[*].author") * </code>
* </code> * </p>
* <p/> * Or:
* If the json path returns a single value (is definite): * <p/>
* </p> * <code>
* <code> * List&lt;Object&gt; authors = JsonPath.read(json, "$.store.book[*].author")
* String author = JsonPath.read(json, "$.store.book[1].author") * </code>
* </code> * <p/>
*/ * If the json path returns a single value (is definite):
public class JsonPath { * </p>
* <code>
public final static int STRICT_MODE = 0; * String author = JsonPath.read(json, "$.store.book[1].author")
public final static int SLACK_MODE = -1; * </code>
*/
private static int mode = SLACK_MODE; public class JsonPath {
private final static Logger log = Logger.getLogger(JsonPath.class.getName()); public final static int STRICT_MODE = 0;
public final static int SLACK_MODE = -1;
private static JSONParser JSON_PARSER = new JSONParser(JsonPath.mode);
// private static int mode = SLACK_MODE;
private JsonPathFilterChain filters; private static JsonFactory factory;
public static void setMode(int mode){ private final static Logger log = Logger.getLogger(JsonPath.class.getName());
if(mode != JsonPath.mode){
JsonPath.mode = mode;
JSON_PARSER = new JSONParser(JsonPath.mode);
} private JsonPathFilterChain filters;
}
/*
public static int getMode(){ public static void setMode(int mode){
return mode; if(mode != JsonPath.mode){
} JsonPath.mode = mode;
JSON_PARSER = new JSONParser(JsonPath.mode);
}
/** }
* Creates a new JsonPath. */
* /*
* @param jsonPath the path statement public static int getMode(){
*/ return mode;
private JsonPath(String jsonPath) { }
if (jsonPath == null || */
jsonPath.trim().isEmpty() ||
jsonPath.matches("new ") || /**
jsonPath.matches("[^\\?\\+\\=\\-\\*\\/\\!]\\(")) { * Creates a new JsonPath.
*
throw new InvalidPathException("Invalid path"); * @param jsonPath the path statement
} */
this.filters = new JsonPathFilterChain(PathUtil.splitPath(jsonPath)); private JsonPath(String jsonPath) {
} if (jsonPath == null ||
jsonPath.trim().isEmpty() ||
/** jsonPath.matches("new ") ||
* Applies this json path to the provided object jsonPath.matches("[^\\?\\+\\=\\-\\*\\/\\!]\\(")) {
*
* @param json a json Object throw new InvalidPathException("Invalid path");
* @param <T> }
* @return list of objects matched by the given path this.filters = new JsonPathFilterChain(PathUtil.splitPath(jsonPath));
*/ }
public <T> T read(Object json) {
FilterOutput filterOutput = filters.filter(json); /**
* Applies this json path to the provided object
if (filterOutput == null || filterOutput.getResult() == null) { *
return null; * @param json a json Object
} * @param <T>
* @return list of objects matched by the given path
return (T) filterOutput.getResult(); * @throws JsonException
} */
public JsonElement read(JsonElement json) throws JsonException {
/** FilterOutput filterOutput = filters.filter(json);
* Applies this json path to the provided object
* if (filterOutput == null || filterOutput.getResult() == null) {
* @param json a json string return null;
* @param <T> }
* @return list of objects matched by the given path
*/ return filterOutput.getResult();
public <T> T read(String json) throws java.text.ParseException {
return (T) read(parse(json)); }
}
/**
/** * Applies this json path to the provided object
* Compiles a JsonPath from the given string *
* * @param json a json string
* @param jsonPath to compile * @param <T>
* @return compiled JsonPath * @return list of objects matched by the given path
*/ * @throws JsonException
public static JsonPath compile(String jsonPath) { */
return new JsonPath(jsonPath); public JsonElement read(String json) throws java.text.ParseException, JsonException {
} return read(parse(json));
}
/**
* Creates a new JsonPath and applies it to the provided Json string /**
* * Compiles a JsonPath from the given string
* @param json a json string *
* @param jsonPath the json path * @param jsonPath to compile
* @param <T> * @return compiled JsonPath
* @return list of objects matched by the given path */
*/ public static JsonPath compile(String jsonPath) {
public static <T> T read(String json, String jsonPath) throws java.text.ParseException { return new JsonPath(jsonPath);
return (T) compile(jsonPath).read(json); }
}
/**
/** * Creates a new JsonPath and applies it to the provided Json string
* Creates a new JsonPath and applies it to the provided Json object *
* * @param json a json string
* @param json a json object * @param jsonPath the json path
* @param jsonPath the json path * @param <T>
* @param <T> * @return list of objects matched by the given path
* @return list of objects matched by the given path * @throws JsonException
*/ */
public static <T> T read(Object json, String jsonPath) { public static JsonElement read(String json, String jsonPath) throws java.text.ParseException, JsonException {
return (T) compile(jsonPath).read(json); return compile(jsonPath).read(json);
} }
/**
private static Object parse(String json) throws java.text.ParseException { * Creates a new JsonPath and applies it to the provided Json object
try { *
return JSON_PARSER.parse(json); * @param json a json object
} catch (ParseException e) { * @param jsonPath the json path
throw new java.text.ParseException(json, e.getPosition()); * @param <T>
} catch (IOException e) { * @return list of objects matched by the given path
throw new RuntimeException(e); * @throws JsonException
} */
} public static JsonElement read(JsonElement json, String jsonPath) throws JsonException {
} return compile(jsonPath).read(json);
}
public static JsonElement parse(String json) {
try {
return JsonFactory.getInstance().parse(json);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (com.jayway.jsonpath.json.ParseException e) {
throw new RuntimeException(e);
}
}
}

142
json-path/src/main/java/com/jayway/jsonpath/PathUtil.java

@ -1,71 +1,71 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
/** /**
* User: kalle stenflo * User: kalle stenflo
* Date: 2/2/11 * Date: 2/2/11
* Time: 2:08 PM * Time: 2:08 PM
*/ */
public class PathUtil { public class PathUtil {
/** /**
* Checks if a path points to a single item or if it potentially returns multiple items * Checks if a path points to a single item or if it potentially returns multiple items
* *
* a path is considered <strong>not</strong> definite if it contains a scan fragment ".." * a path is considered <strong>not</strong> definite if it contains a scan fragment ".."
* or an array position fragment that is not based on a single index * or an array position fragment that is not based on a single index
* *
* *
* absolute path examples: * absolute path examples:
* *
* $store.book * $store.book
* $store.book[1].value * $store.book[1].value
* *
* not absolute path examples * not absolute path examples
* *
* $..book * $..book
* $.store.book[1,2] * $.store.book[1,2]
* $.store.book[?(@.category = 'fiction')] * $.store.book[?(@.category = 'fiction')]
* *
* @param jsonPath the path to check * @param jsonPath the path to check
* @return true if path is definite (points to single item) * @return true if path is definite (points to single item)
*/ */
public static boolean isPathDefinite(String jsonPath) { public static boolean isPathDefinite(String jsonPath) {
//return !jsonPath.replaceAll("\"[^\"\\\\\\n\r]*\"", "").matches(".*(\\.\\.|\\*|\\[[\\\\/]|\\?|,|:|>|\\(|<|=|\\+).*"); //return !jsonPath.replaceAll("\"[^\"\\\\\\n\r]*\"", "").matches(".*(\\.\\.|\\*|\\[[\\\\/]|\\?|,|:|>|\\(|<|=|\\+).*");
return !jsonPath.replaceAll("\"[^\"\\\\\\n\r]*\"", "").matches(".*(\\.\\.|\\*|\\[[\\\\/]|\\?|,|:\\s?\\]|\\[\\s?:|>|\\(|<|=|\\+).*"); return !jsonPath.replaceAll("\"[^\"\\\\\\n\r]*\"", "").matches(".*(\\.\\.|\\*|\\[[\\\\/]|\\?|,|:\\s?\\]|\\[\\s?:|>|\\(|<|=|\\+).*");
} }
/** /**
* Splits a path into fragments * Splits a path into fragments
* *
* the path <code>$.store.book[1].category</code> returns ["$", "store", "book", "[1]", "value"] * the path <code>$.store.book[1].category</code> returns ["$", "store", "book", "[1]", "value"]
* *
* @param jsonPath path to split * @param jsonPath path to split
* @return fragments * @return fragments
*/ */
public static List<String> splitPath(String jsonPath) { public static List<String> splitPath(String jsonPath) {
LinkedList<String> fragments = new LinkedList<String>(); LinkedList<String> fragments = new LinkedList<String>();
if (!jsonPath.startsWith("$.")) { if (!jsonPath.startsWith("$.")) {
jsonPath = "$." + jsonPath; jsonPath = "$." + jsonPath;
} }
jsonPath = jsonPath.replace("..", ".~.") jsonPath = jsonPath.replace("..", ".~.")
.replace("[", ".[") .replace("[", ".[")
.replace("@.", "@") .replace("@.", "@")
.replace("['", "") .replace("['", "")
.replace("']", ""); .replace("']", "");
String[] split = jsonPath.split("\\."); String[] split = jsonPath.split("\\.");
for (int i = 0; i < split.length; i++) { for (int i = 0; i < split.length; i++) {
if (split[i].trim().isEmpty()) { if (split[i].trim().isEmpty()) {
continue; continue;
} }
fragments.add(split[i].replace("@", "@.").replace("~", "..")); fragments.add(split[i].replace("@", "@.").replace("~", ".."));
} }
return fragments; return fragments;
} }
} }

176
json-path/src/main/java/com/jayway/jsonpath/eval/ExpressionEvaluator.java

@ -1,88 +1,88 @@
package com.jayway.jsonpath.eval; package com.jayway.jsonpath.eval;
/** /**
* User: kalle stenflo * User: kalle stenflo
* Date: 2/4/11 * Date: 2/4/11
* Time: 9:21 PM * Time: 9:21 PM
*/ */
public class ExpressionEvaluator { public class ExpressionEvaluator {
public static <T> boolean eval(T actual, String comparator, String expected) { public static <T> boolean eval(T actual, String comparator, String expected) {
comparator = comparator.trim(); comparator = comparator.trim();
if (actual instanceof Long) { if (actual instanceof Long) {
Long a = (Long) actual; Long a = (Long) actual;
Long e = Long.parseLong(expected.trim()); Long e = Long.parseLong(expected.trim());
if ("=".equals(comparator)) { if ("=".equals(comparator)) {
return a.longValue() == e.longValue(); return a.longValue() == e.longValue();
} else if ("!=".equals(comparator) || "<>".equals(comparator)) { } else if ("!=".equals(comparator) || "<>".equals(comparator)) {
return a.longValue() != e.longValue(); return a.longValue() != e.longValue();
} else if (">".equals(comparator)) { } else if (">".equals(comparator)) {
return a.longValue() > e.longValue(); return a.longValue() > e.longValue();
} else if (">=".equals(comparator)) { } else if (">=".equals(comparator)) {
return a.longValue() >= e.longValue(); return a.longValue() >= e.longValue();
} else if ("<".equals(comparator)) { } else if ("<".equals(comparator)) {
return a.longValue() < e.longValue(); return a.longValue() < e.longValue();
} else if ("<=".equals(comparator)) { } else if ("<=".equals(comparator)) {
return a.longValue() <= e.longValue(); return a.longValue() <= e.longValue();
} }
} else if (actual instanceof Integer) { } else if (actual instanceof Integer) {
Integer a = (Integer) actual; Integer a = (Integer) actual;
Integer e = Integer.parseInt(expected.trim()); Integer e = Integer.parseInt(expected.trim());
if ("=".equals(comparator)) { if ("=".equals(comparator)) {
return a.intValue() == e.intValue(); return a.intValue() == e.intValue();
} else if ("!=".equals(comparator) || "<>".equals(comparator)) { } else if ("!=".equals(comparator) || "<>".equals(comparator)) {
return a.intValue() != e.intValue(); return a.intValue() != e.intValue();
} else if (">".equals(comparator)) { } else if (">".equals(comparator)) {
return a.intValue() > e.intValue(); return a.intValue() > e.intValue();
} else if (">=".equals(comparator)) { } else if (">=".equals(comparator)) {
return a.intValue() >= e.intValue(); return a.intValue() >= e.intValue();
} else if ("<".equals(comparator)) { } else if ("<".equals(comparator)) {
return a.intValue() < e.intValue(); return a.intValue() < e.intValue();
} else if ("<=".equals(comparator)) { } else if ("<=".equals(comparator)) {
return a.intValue() <= e.intValue(); return a.intValue() <= e.intValue();
} }
} else if (actual instanceof Double) { } else if (actual instanceof Double) {
Double a = (Double) actual; Double a = (Double) actual;
Double e = Double.parseDouble(expected.trim()); Double e = Double.parseDouble(expected.trim());
if ("=".equals(comparator)) { if ("=".equals(comparator)) {
return a.doubleValue() == e.doubleValue(); return a.doubleValue() == e.doubleValue();
} else if ("!=".equals(comparator) || "<>".equals(comparator)) { } else if ("!=".equals(comparator) || "<>".equals(comparator)) {
return a.doubleValue() != e.doubleValue(); return a.doubleValue() != e.doubleValue();
} else if (">".equals(comparator)) { } else if (">".equals(comparator)) {
return a.doubleValue() > e.doubleValue(); return a.doubleValue() > e.doubleValue();
} else if (">=".equals(comparator)) { } else if (">=".equals(comparator)) {
return a.doubleValue() >= e.doubleValue(); return a.doubleValue() >= e.doubleValue();
} else if ("<".equals(comparator)) { } else if ("<".equals(comparator)) {
return a.doubleValue() < e.doubleValue(); return a.doubleValue() < e.doubleValue();
} else if ("<=".equals(comparator)) { } else if ("<=".equals(comparator)) {
return a.doubleValue() <= e.doubleValue(); return a.doubleValue() <= e.doubleValue();
} }
} else if (actual instanceof String) { } else if (actual instanceof String) {
String a = (String)actual; String a = (String)actual;
expected = expected.trim(); expected = expected.trim();
if(expected.startsWith("'")) { if(expected.startsWith("'")) {
expected = expected.substring(1); expected = expected.substring(1);
} }
if(expected.endsWith("'")){ if(expected.endsWith("'")){
expected = expected.substring(0, expected.length()-1); expected = expected.substring(0, expected.length()-1);
} }
if ("=".equals(comparator)) { if ("=".equals(comparator)) {
return a.equals(expected); return a.equals(expected);
} else if ("!=".equals(comparator) || "<>".equals(comparator)) { } else if ("!=".equals(comparator) || "<>".equals(comparator)) {
return !a.equals(expected); return !a.equals(expected);
} }
} }
return false; return false;
} }
} }

105
json-path/src/main/java/com/jayway/jsonpath/filter/FilterOutput.java

@ -1,39 +1,66 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import java.util.List; import java.util.ArrayList;
import java.util.List;
import static java.lang.String.format;
import com.jayway.jsonpath.json.JsonArray;
/** import com.jayway.jsonpath.json.JsonElement;
* User: kalle stenflo import com.jayway.jsonpath.json.JsonException;
* Date: 2/9/11 import com.jayway.jsonpath.json.JsonFactory;
* Time: 12:28 PM
*/ import static java.lang.String.format;
public class FilterOutput {
/**
private final Object result; * User: kalle stenflo
* Date: 2/9/11
public FilterOutput(Object result) { * Time: 12:28 PM
this.result = result; */
} public class FilterOutput {
private final List<JsonElement> result;
public boolean isList(){
public FilterOutput(JsonElement root) {
return (result instanceof List); this.result = new ArrayList<JsonElement>();
result.add(root);
} }
public Object getResult() {
return result; public FilterOutput(List<JsonElement> result) {
} this.result = result;
public List<Object> getResultAsList() { }
if(!isList()){
throw new RuntimeException(format("Can not convert a %s to a %s", result.getClass().getName(), List.class.getName()));
} public FilterOutput() {
return (List<Object>)result; this.result = new ArrayList<JsonElement>();
} }
public JsonElement getResult() throws JsonException {
} if(result.size()==0){
return null;
}
else if(result.size()==1){
return result.get(0);
}
else{
JsonFactory fact = JsonFactory.getInstance();
JsonArray ja = fact.createJsonArray();
for(JsonElement ele:result)
ja.add(ele);
return ja;
}
}
public JsonArray getResultAsList() throws JsonException {
return getResult().toJsonArray();
}
public List<JsonElement> getList() throws JsonException {
return result;
}
}

41
json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterBase.java

@ -1,13 +1,28 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import java.util.List; import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA. import com.jayway.jsonpath.json.JsonElement;
* User: kallestenflo import com.jayway.jsonpath.json.JsonException;
* Date: 2/2/11
* Time: 2:01 PM /**
*/ * Created by IntelliJ IDEA.
public abstract class JsonPathFilterBase { * User: kallestenflo
public abstract FilterOutput apply(FilterOutput filterItems); * Date: 2/2/11
} * Time: 2:01 PM
*/
public abstract class JsonPathFilterBase {
public FilterOutput apply(FilterOutput element) throws JsonException{
List<JsonElement> result = new ArrayList<JsonElement>();
for(JsonElement el : element.getList()){
List<JsonElement> out = apply(el);
if(out != null)
result.addAll(out);
}
return new FilterOutput(result);
}
public abstract List<JsonElement> apply(JsonElement element) throws JsonException;
public abstract String getPathSegment() throws JsonException;;
}

109
json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterChain.java

@ -1,47 +1,62 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import com.jayway.jsonpath.InvalidPathException; import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.json.JsonElement;
import java.util.LinkedList; import com.jayway.jsonpath.json.JsonException;
import java.util.List;
import java.util.ArrayList;
/** import java.util.LinkedList;
* User: kallestenflo import java.util.List;
* Date: 2/2/11 import java.util.Stack;
* Time: 2:00 PM
*/ import org.apache.log4j.Logger;
public class JsonPathFilterChain {
/**
private List<JsonPathFilterBase> filters; * User: kallestenflo
* Date: 2/2/11
public JsonPathFilterChain(List<String> pathFragments) { * Time: 2:00 PM
filters = configureFilters(pathFragments); */
} public class JsonPathFilterChain {
private List<JsonPathFilterBase> configureFilters(List<String> pathFragments) { private List<JsonPathFilterBase> filters;
private JsonElement payload = null;
List<JsonPathFilterBase> configured = new LinkedList<JsonPathFilterBase>(); private final Logger log = Logger.getLogger(JsonPathFilterChain.class);
for (String pathFragment : pathFragments) { public JsonPathFilterChain(List<String> pathFragments) {
configured.add(JsonPathFilterFactory.createFilter(pathFragment)); filters = configureFilters(pathFragments);
} }
return configured;
} public JsonPathFilterChain(List<String> pathFragments,JsonElement payload) {
filters = configureFilters(pathFragments);
public FilterOutput filter(Object root) { this.payload = payload;
}
FilterOutput out = new FilterOutput(root);
private List<JsonPathFilterBase> configureFilters(List<String> pathFragments) {
for (JsonPathFilterBase filter : filters) {
if (filter == null) { List<JsonPathFilterBase> configured = new LinkedList<JsonPathFilterBase>();
throw new InvalidPathException();
} for (String pathFragment : pathFragments) {
if(out.getResult() == null){ configured.add(JsonPathFilterFactory.createFilter(pathFragment));
return null; }
} return configured;
out = filter.apply(out); }
}
public FilterOutput filter(JsonElement root) throws JsonException {
return out; FilterOutput out = new FilterOutput(root);
} log.info(out.getResult().toString());
} for (JsonPathFilterBase filter : filters) {
if (filter == null) {
throw new InvalidPathException();
}
if(out.getList() == null){
return null;
}
out = filter.apply(out);
if(out.getResult()!=null)
log.info(out.getResult().toString());
}
return out;
}
}

80
json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterFactory.java

@ -1,37 +1,43 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
/** /**
* User: kallestenflo * User: kallestenflo
* Date: 2/2/11 * Date: 2/2/11
* Time: 2:03 PM * Time: 2:03 PM
*/ */
public class JsonPathFilterFactory { public class JsonPathFilterFactory {
public static JsonPathFilterBase createFilter(String pathFragment) { public static JsonPathFilterBase createFilter(String pathFragment) {
if (RootFilter.PATTERN.matcher(pathFragment).matches()) { if (RootFilter.PATTERN.matcher(pathFragment).matches()) {
return new RootFilter(); return new RootFilter();
} else if (ListIndexFilter.PATTERN.matcher(pathFragment).matches()) { } else if (ListIndexFilter.PATTERN.matcher(pathFragment).matches()) {
return new ListIndexFilter(pathFragment); return new ListIndexFilter(pathFragment);
} else if (ListFrontFilter.PATTERN.matcher(pathFragment).matches()) { } else if (ListFrontFilter.PATTERN.matcher(pathFragment).matches()) {
return new ListFrontFilter(pathFragment); return new ListFrontFilter(pathFragment);
} else if (ListWildcardFilter.PATTERN.matcher(pathFragment).matches()) { } else if (ListWildcardFilter.PATTERN.matcher(pathFragment).matches()) {
return new ListWildcardFilter(); return new ListWildcardFilter();
} else if (ListTailFilter.PATTERN.matcher(pathFragment).matches()) { } else if (ListTailFilter.PATTERN.matcher(pathFragment).matches()) {
return new ListTailFilter(pathFragment); return new ListTailFilter(pathFragment);
} else if (ListPropertyFilter.PATTERN.matcher(pathFragment).matches()) { } else if (ListPropertyFilter.PATTERN.matcher(pathFragment).matches()) {
return new ListPropertyFilter(pathFragment); return new ListPropertyFilter(pathFragment);
} else if (ListEvalFilter.PATTERN.matcher(pathFragment).matches()) { } else if (ListEvalFilter.PATTERN.matcher(pathFragment).matches()) {
return new ListEvalFilter(pathFragment); return new ListEvalFilter(pathFragment);
} else if (TraverseFilter.PATTERN.matcher(pathFragment).matches()) { } else if (TraverseFilter.PATTERN.matcher(pathFragment).matches()) {
return new TraverseFilter(); return new TraverseFilter();
} else if (WildcardPropertyFilter.PATTERN.matcher(pathFragment).matches()) { } else if (WildcardPropertyFilter.PATTERN.matcher(pathFragment).matches()) {
return new WildcardPropertyFilter(); return new WildcardPropertyFilter();
} else if (PropertyFilter.PATTERN.matcher(pathFragment).matches()) { }else if (M4PropertyFilter.PATTERN.matcher(pathFragment).matches()) {
return new PropertyFilter(pathFragment); return new M4PropertyFilter(pathFragment);
} }
return null; else if (TypeFilter.PATTERN.matcher(pathFragment).matches()) {
return new TypeFilter(pathFragment);
} }else if (PropertyFilter.PATTERN.matcher(pathFragment).matches()) {
return new PropertyFilter(pathFragment);
} }
return null;
}
}

164
json-path/src/main/java/com/jayway/jsonpath/filter/ListEvalFilter.java

@ -1,73 +1,91 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import com.jayway.jsonpath.JsonUtil;
import com.jayway.jsonpath.eval.ExpressionEvaluator; import com.jayway.jsonpath.eval.ExpressionEvaluator;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonArray;
import com.jayway.jsonpath.json.JsonElement;
import java.util.List; import com.jayway.jsonpath.json.JsonException;
import java.util.Map; import com.jayway.jsonpath.json.JsonFactory;
import java.util.regex.Matcher; import com.jayway.jsonpath.json.JsonObject;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA. import java.util.ArrayList;
* User: kallestenflo import java.util.List;
* Date: 2/15/11 import java.util.regex.Matcher;
* Time: 8:27 PM import java.util.regex.Pattern;
*/
public class ListEvalFilter extends JsonPathFilterBase { /**
* Created by IntelliJ IDEA.
* User: kallestenflo
public static final Pattern PATTERN = Pattern.compile("\\[\\s?\\?\\s?\\(\\s?@.(\\w+)\\s?([=<>]+)\\s?(.*)\\s?\\)\\s?\\]"); //[?( @.title< 'ko')] * Date: 2/15/11
* Time: 8:27 PM
private final String pathFragment; */
public class ListEvalFilter extends JsonPathFilterBase {
public ListEvalFilter(String pathFragment) {
this.pathFragment = pathFragment; //@Autowired
} public JsonFactory factory = com.jayway.jsonpath.json.minidev.MiniJsonFactory.getInstance();
public static final Pattern PATTERN = Pattern.compile("\\[\\s?\\?\\s?\\(\\s?@.(\\w+)\\s?([=<>]+)\\s?(.*)\\s?\\)\\s?\\]"); //[?( @.title< 'ko')]
@Override
public FilterOutput apply(FilterOutput filterItems) { private final String pathFragment;
List<Object> result = new JSONArray(); public ListEvalFilter(String pathFragment) {
this.pathFragment = pathFragment;
for (Object item : filterItems.getResultAsList()) { }
if (isMatch(item)) {
result.add(item);
} @Override
} public List<JsonElement> apply(JsonElement element) throws JsonException {
return new FilterOutput(result); List<JsonElement> result = new ArrayList<JsonElement>();
}
if(element.isJsonArray()){
private boolean isMatch(Object check) { for(JsonElement subElement: element.toJsonArray()){
Matcher matcher = PATTERN.matcher(pathFragment); if (isMatch(subElement)) {
result.add(subElement);
if (matcher.matches()) { }
String property = matcher.group(1); }
String operator = matcher.group(2); }
String expected = matcher.group(3);
return result;
if (!JsonUtil.isMap(check)) {
return false; }
}
Map obj = JsonUtil.toMap(check); private boolean isMatch(JsonElement check) throws JsonException {
Matcher matcher = PATTERN.matcher(pathFragment);
if (!obj.containsKey(property)) {
return false; if (matcher.matches()) {
} String property = matcher.group(1);
String operator = matcher.group(2);
Object propertyValue = obj.get(property); String expected = matcher.group(3);
if (JsonUtil.isContainer(propertyValue)) { if (!check.isJsonObject()) {
return false; return false;
} }
String expression = propertyValue + " " + operator + " " + expected; JsonObject obj = check.toJsonObject();
return ExpressionEvaluator.eval(propertyValue, operator, expected); if (!obj.hasProperty(property)) {
return false;
} }
return false;
} JsonElement propertyValue = obj.getProperty(property);
}
if (propertyValue.isContainer()) {
return false;
}
String expression = propertyValue.toObject() + " " + operator + " " + expected;
return ExpressionEvaluator.eval(propertyValue.toObject(), operator, expected);
}
return false;
}
@Override
public String getPathSegment() throws JsonException {
return pathFragment;
}
}

148
json-path/src/main/java/com/jayway/jsonpath/filter/ListFrontFilter.java

@ -1,67 +1,81 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonArray;
import com.jayway.jsonpath.json.JsonElement;
import java.util.LinkedList; import com.jayway.jsonpath.json.JsonException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.ArrayList;
import java.util.LinkedList;
/** import java.util.List;
* Created by IntelliJ IDEA. import java.util.regex.Matcher;
* User: kallestenflo import java.util.regex.Pattern;
* Date: 2/15/11
* Time: 8:20 PM
*/
public class ListFrontFilter extends JsonPathFilterBase { /**
* Created by IntelliJ IDEA.
* User: kallestenflo
public static final Pattern PATTERN = Pattern.compile("\\[\\s?:(\\d+)\\s?\\]"); //[ :2 ] * Date: 2/15/11
* Time: 8:20 PM
private final String pathFragment; */
public class ListFrontFilter extends JsonPathFilterBase {
public ListFrontFilter(String pathFragment) {
this.pathFragment = pathFragment; //@Autowired
} public com.jayway.jsonpath.json.JsonFactory factory = com.jayway.jsonpath.json.minidev.MiniJsonFactory.getInstance();
@Override public static final Pattern PATTERN = Pattern.compile("\\[\\s?:(\\d+)\\s?\\]"); //[ :2 ]
public FilterOutput apply(FilterOutput filterItems) {
private final String pathFragment;
List<Object> result = new JSONArray();
Integer[] index = getListPullIndex(); @Override
for (int i : index) { public String getPathSegment() throws JsonException {
if (indexIsInRange(filterItems.getResultAsList(), i)) { return pathFragment;
result.add(filterItems.getResultAsList().get(i)); }
} public ListFrontFilter(String pathFragment) {
} this.pathFragment = pathFragment;
return new FilterOutput(result); }
}
@Override
public List<JsonElement> apply(JsonElement element) throws JsonException {
private Integer[] getListPullIndex() { List<JsonElement> result = new ArrayList<JsonElement>();
Matcher matcher = PATTERN.matcher(pathFragment); if(element.isJsonArray()){
if (matcher.matches()) { Integer[] index = getListPullIndex();
for (int i : index) {
int pullCount = Integer.parseInt(matcher.group(1)); if (indexIsInRange(element.toJsonArray(), i)) {
result.add(element.toJsonArray().get(i));
List<Integer> result = new LinkedList<Integer>(); }
}
for (int y = 0; y < pullCount; y++) { }
result.add(y); return result;
} }
return result.toArray(new Integer[0]);
}
throw new IllegalArgumentException("invalid list index"); private Integer[] getListPullIndex() {
} Matcher matcher = PATTERN.matcher(pathFragment);
if (matcher.matches()) {
private boolean indexIsInRange(List list, int index) {
if (index < 0) { int pullCount = Integer.parseInt(matcher.group(1));
return false;
} else if (index > list.size() - 1) { List<Integer> result = new LinkedList<Integer>();
return false;
} else { for (int y = 0; y < pullCount; y++) {
return true; result.add(y);
} }
} return result.toArray(new Integer[0]);
} }
throw new IllegalArgumentException("invalid list index");
}
private boolean indexIsInRange(List list, int index) {
if (index < 0) {
return false;
} else if (index > list.size() - 1) {
return false;
} else {
return true;
}
}
}

150
json-path/src/main/java/com/jayway/jsonpath/filter/ListIndexFilter.java

@ -1,72 +1,78 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import net.minidev.json.JSONArray;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.LinkedList;
import java.util.regex.Pattern; import java.util.List;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA. import com.jayway.jsonpath.json.JsonArray;
* User: kallestenflo import com.jayway.jsonpath.json.JsonElement;
* Date: 2/15/11 import com.jayway.jsonpath.json.JsonException;
* Time: 8:02 PM
*/ /**
public class ListIndexFilter extends JsonPathFilterBase { * Created by IntelliJ IDEA.
* User: kallestenflo
public static final Pattern PATTERN = Pattern.compile("\\[(\\s?\\d+\\s?,?)+\\]"); //[1] OR [1,2,3] * Date: 2/15/11
* Time: 8:02 PM
private final String pathFragment; */
public class ListIndexFilter extends JsonPathFilterBase {
public ListIndexFilter(String pathFragment) {
this.pathFragment = pathFragment; public static final Pattern PATTERN = Pattern.compile("\\[(\\s?\\d+\\s?,?)+\\]"); //[1] OR [1,2,3]
}
private final String pathFragment;
@Override @Override
public FilterOutput apply(FilterOutput filterItems) { public String getPathSegment() throws JsonException {
return pathFragment;
Object result = null; }
//@Autowired
Integer[] index = getArrayIndex(); public com.jayway.jsonpath.json.JsonFactory factory = com.jayway.jsonpath.json.minidev.MiniJsonFactory.getInstance();
if (index.length > 1) {
List<Object> tmp = new JSONArray(); public ListIndexFilter(String pathFragment) {
for (int i : index) { this.pathFragment = pathFragment;
if (indexIsInRange(filterItems.getResultAsList(), i)) { }
tmp.add(filterItems.getResultAsList().get(i));
} @Override
} public List<JsonElement> apply(JsonElement element) throws JsonException {
result = tmp; List<JsonElement> result = new ArrayList<JsonElement>();
} else {
if (indexIsInRange(filterItems.getResultAsList(), index[0])) { Integer[] index = getArrayIndex();
result = filterItems.getResultAsList().get(index[0]); if(element.isJsonArray()){
} for (int i : index) {
} if (indexIsInRange(element.toJsonArray(), i)) {
return new FilterOutput(result); result.add(element.toJsonArray().get(i));
} }
}
private boolean indexIsInRange(List list, int index) { }
if (index < 0) {
return false;
} else if (index > list.size() - 1) { return result;
return false; }
} else {
return true; private boolean indexIsInRange(List list, int index) {
} if (index < 0) {
} return false;
} else if (index > list.size() - 1) {
return false;
private Integer[] getArrayIndex() { } else {
return true;
String prepared = pathFragment.replaceAll(" ", ""); }
prepared = prepared.substring(1, prepared.length() - 1); }
List<Integer> index = new LinkedList<Integer>();
private Integer[] getArrayIndex() {
String[] split = prepared.split(",");
String prepared = pathFragment.replaceAll(" ", "");
for (String s : split) { prepared = prepared.substring(1, prepared.length() - 1);
index.add(Integer.parseInt(s));
} List<Integer> index = new LinkedList<Integer>();
return index.toArray(new Integer[0]);
} String[] split = prepared.split(",");
}
for (String s : split) {
index.add(Integer.parseInt(s));
}
return index.toArray(new Integer[0]);
}
}

114
json-path/src/main/java/com/jayway/jsonpath/filter/ListPropertyFilter.java

@ -1,52 +1,62 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import com.jayway.jsonpath.JsonUtil;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonArray;
import com.jayway.jsonpath.json.JsonElement;
import java.util.List; import com.jayway.jsonpath.json.JsonException;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.ArrayList;
import java.util.List;
/** import java.util.regex.Matcher;
* Created by IntelliJ IDEA. import java.util.regex.Pattern;
* User: kallestenflo
* Date: 2/15/11 /**
* Time: 8:23 PM * Created by IntelliJ IDEA.
*/ * User: kallestenflo
public class ListPropertyFilter extends JsonPathFilterBase { * Date: 2/15/11
* Time: 8:23 PM
public static final Pattern PATTERN = Pattern.compile("\\[\\s?\\?\\s?\\(\\s?@\\.(\\w+)\\s?\\)\\s?\\]"); //[?(@.title)] */
public class ListPropertyFilter extends JsonPathFilterBase {
private final String pathFragment;
//@Autowired
public ListPropertyFilter(String pathFragment) { public com.jayway.jsonpath.json.JsonFactory factory = com.jayway.jsonpath.json.minidev.MiniJsonFactory.getInstance();
this.pathFragment = pathFragment;
} public static final Pattern PATTERN = Pattern.compile("\\[\\s?\\?\\s?\\(\\s?@\\.(\\w+)\\s?\\)\\s?\\]"); //[?(@.title)]
@Override private final String pathFragment;
public FilterOutput apply(FilterOutput filterItems) {
public ListPropertyFilter(String pathFragment) {
List<Object> result = new JSONArray(); this.pathFragment = pathFragment;
}
String prop = getFilterProperty(); @Override
public String getPathSegment() throws JsonException {
for (Object item : filterItems.getResultAsList()) { return pathFragment;
}
if (JsonUtil.isMap(item)) { @Override
if (JsonUtil.toMap(item).containsKey(prop)) { public List<JsonElement> apply(JsonElement element) throws JsonException {
result.add(item); List<JsonElement> result = new ArrayList<JsonElement>();
}
} String prop = getFilterProperty();
}
return new FilterOutput(result); if(element.isJsonArray()){
} for(JsonElement subElement : element.toJsonArray()){
if (subElement.isJsonObject()) {
if (subElement.toJsonObject().hasProperty(prop)) {
private String getFilterProperty() { result.add(subElement);
Matcher matcher = PATTERN.matcher(pathFragment); }
if (matcher.matches()) { }
return matcher.group(1); }
} }
throw new IllegalArgumentException("invalid list filter property");
} return result;
} }
private String getFilterProperty() {
Matcher matcher = PATTERN.matcher(pathFragment);
if (matcher.matches()) {
return matcher.group(1);
}
throw new IllegalArgumentException("invalid list filter property");
}
}

125
json-path/src/main/java/com/jayway/jsonpath/filter/ListTailFilter.java

@ -1,56 +1,69 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import java.util.List; import java.util.ArrayList;
import java.util.regex.Matcher; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA. import com.jayway.jsonpath.json.JsonElement;
* User: kallestenflo import com.jayway.jsonpath.json.JsonException;
* Date: 2/15/11
* Time: 8:16 PM /**
*/ * Created by IntelliJ IDEA.
public class ListTailFilter extends JsonPathFilterBase { * User: kallestenflo
* Date: 2/15/11
* Time: 8:16 PM
private static final Pattern LIST_TAIL_PATTERN_SHORT = Pattern.compile("\\[\\s*-\\s*(\\d+):\\s*\\]"); // [(@.length - 12)] OR [-13:] */
private static final Pattern LIST_TAIL_PATTERN_LONG = Pattern.compile("\\[\\s*\\(\\s*@\\.length\\s*-\\s*(\\d+)\\s*\\)\\s*\\]"); //[(@.length-1)] public class ListTailFilter extends JsonPathFilterBase {
public static final Pattern PATTERN = Pattern.compile("(" + LIST_TAIL_PATTERN_SHORT.pattern() + "|" + LIST_TAIL_PATTERN_LONG.pattern() + ")");
private static final Pattern LIST_TAIL_PATTERN_SHORT = Pattern.compile("\\[\\s*-\\s*(\\d+):\\s*\\]"); // [(@.length - 12)] OR [-13:]
private final String pathFragment; private static final Pattern LIST_TAIL_PATTERN_LONG = Pattern.compile("\\[\\s*\\(\\s*@\\.length\\s*-\\s*(\\d+)\\s*\\)\\s*\\]"); //[(@.length-1)]
public ListTailFilter(String pathFragment) { public static final Pattern PATTERN = Pattern.compile("(" + LIST_TAIL_PATTERN_SHORT.pattern() + "|" + LIST_TAIL_PATTERN_LONG.pattern() + ")");
this.pathFragment = pathFragment;
} private final String pathFragment;
@Override public ListTailFilter(String pathFragment) {
public FilterOutput apply(FilterOutput filterItems) { this.pathFragment = pathFragment;
}
int index = getTailIndex(filterItems.getResultAsList().size());
@Override
return new FilterOutput(filterItems.getResultAsList().get(index)); public String getPathSegment() throws JsonException {
} return pathFragment;
}
@Override
private int getTailIndex(int arraySize) { public List<JsonElement> apply(JsonElement element) throws JsonException {
List<JsonElement> result = new ArrayList<JsonElement>();
Matcher matcher = LIST_TAIL_PATTERN_SHORT.matcher(pathFragment);
if (matcher.matches()) { if(element.isJsonArray()){
int index = getTailIndex(element.toJsonArray().size());
int index = Integer.parseInt(matcher.group(1)); result.add(element.toJsonArray().get(index));
}
return arraySize - index;
} return result;
matcher = LIST_TAIL_PATTERN_LONG.matcher(pathFragment);
if (matcher.matches()) { }
int index = Integer.parseInt(matcher.group(1));
private int getTailIndex(int arraySize) {
return arraySize - index;
} Matcher matcher = LIST_TAIL_PATTERN_SHORT.matcher(pathFragment);
if (matcher.matches()) {
throw new IllegalArgumentException("invalid list index");
int index = Integer.parseInt(matcher.group(1));
}
} return arraySize - index;
}
matcher = LIST_TAIL_PATTERN_LONG.matcher(pathFragment);
if (matcher.matches()) {
int index = Integer.parseInt(matcher.group(1));
return arraySize - index;
}
throw new IllegalArgumentException("invalid list index");
}
}

55
json-path/src/main/java/com/jayway/jsonpath/filter/ListWildcardFilter.java

@ -1,19 +1,36 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import java.util.regex.Pattern; import java.util.ArrayList;
import java.util.List;
/** import java.util.regex.Pattern;
* Created by IntelliJ IDEA.
* User: kallestenflo import com.jayway.jsonpath.json.JsonElement;
* Date: 2/15/11 import com.jayway.jsonpath.json.JsonException;
* Time: 8:09 PM
*/ /**
public class ListWildcardFilter extends JsonPathFilterBase{ * Created by IntelliJ IDEA.
* User: kallestenflo
public static final Pattern PATTERN = Pattern.compile("\\[\\*\\]"); * Date: 2/15/11
* Time: 8:09 PM
@Override */
public FilterOutput apply(FilterOutput filterItems) { public class ListWildcardFilter extends JsonPathFilterBase{
return new FilterOutput(filterItems.getResultAsList());
} public static final Pattern PATTERN = Pattern.compile("\\[\\*\\]");
}
@Override
public List<JsonElement> apply(JsonElement element) throws JsonException {
List<JsonElement> result = new ArrayList<JsonElement>();
if(element.isJsonArray()){
for(JsonElement ele : element.toJsonArray()){
result.add(ele);
}
}
return result;
}
@Override
public String getPathSegment() throws JsonException {
return null;
}
}

113
json-path/src/main/java/com/jayway/jsonpath/filter/PropertyFilter.java

@ -1,54 +1,59 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import com.jayway.jsonpath.JsonUtil;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonArray;
import com.jayway.jsonpath.json.JsonElement;
import java.util.List; import com.jayway.jsonpath.json.JsonException;
import java.util.regex.Pattern; import com.jayway.jsonpath.json.JsonFactory;
/**
* Created by IntelliJ IDEA. import java.util.ArrayList;
* User: kallestenflo import java.util.List;
* Date: 2/2/11 import java.util.regex.Pattern;
* Time: 2:32 PM
*/ /**
public class PropertyFilter extends JsonPathFilterBase { * Created by IntelliJ IDEA.
* User: kallestenflo
public final static Pattern PATTERN = Pattern.compile("(.*)|\\['(.*?)'\\]"); * Date: 2/2/11
* Time: 2:32 PM
*/
private final String pathFragment; public class PropertyFilter extends JsonPathFilterBase {
public PropertyFilter(String pathFragment) { public final static Pattern PATTERN = Pattern.compile("(.*)|\\['(.*?)'\\]");
this.pathFragment = pathFragment;
}
private final String pathFragment;
@Override
public FilterOutput apply(FilterOutput filter) {
private JsonFactory factory = com.jayway.jsonpath.json.minidev.MiniJsonFactory.getInstance();
List<Object> result = new JSONArray();
public PropertyFilter(String pathFragment) {
this.pathFragment = pathFragment;
if (filter.isList()) { }
for (Object current : filter.getResultAsList()) {
if (JsonUtil.toMap(current).containsKey(pathFragment)) { @Override
public String getPathSegment() throws JsonException {
Object o = JsonUtil.toMap(current).get(pathFragment); return null;
if (JsonUtil.isList(o)) { }
result.addAll(JsonUtil.toList(o));
@Override
} else { public List<JsonElement> apply(JsonElement element) throws JsonException {
result.add(JsonUtil.toMap(current).get(pathFragment));
} List<JsonElement> result = new ArrayList<JsonElement>();
}
} if (element.isJsonObject() && element.toJsonObject().hasProperty(pathFragment)) {
return new FilterOutput(result); JsonElement o = element.toJsonObject().getProperty(pathFragment);
} else { if(o != null){
Object mapValue = null; result.add(o);
if (JsonUtil.toMap(filter.getResult()).containsKey(pathFragment)) { }
mapValue = JsonUtil.toMap(filter.getResult()).get(pathFragment); else{
} result.add(factory.createJsonNull(pathFragment,element));
return new FilterOutput(mapValue); }
} }
} else if(element.isJsonObject()){
} result.add(factory.createJsonNull(pathFragment,element));
}
return result;
}
}

52
json-path/src/main/java/com/jayway/jsonpath/filter/RootFilter.java

@ -1,20 +1,32 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import java.util.List; import java.util.ArrayList;
import java.util.regex.Pattern; import java.util.List;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA. import com.jayway.jsonpath.json.JsonElement;
* User: kallestenflo import com.jayway.jsonpath.json.JsonException;
* Date: 2/2/11
* Time: 2:31 PM /**
*/ * Created by IntelliJ IDEA.
public class RootFilter extends JsonPathFilterBase{ * User: kallestenflo
* Date: 2/2/11
public final static Pattern PATTERN = Pattern.compile("\\$"); * Time: 2:31 PM
*/
@Override public class RootFilter extends JsonPathFilterBase{
public FilterOutput apply(FilterOutput root) {
return root; public final static Pattern PATTERN = Pattern.compile("\\$");
}
} @Override
public List<JsonElement> apply(JsonElement element) throws JsonException {
List<JsonElement> result = new ArrayList<JsonElement>();
result.add(element);
return result;
}
@Override
public String getPathSegment() throws JsonException {
return null;
}
}

103
json-path/src/main/java/com/jayway/jsonpath/filter/TraverseFilter.java

@ -1,48 +1,57 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import com.jayway.jsonpath.JsonUtil; import com.jayway.jsonpath.json.JsonArray;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonElement;
import com.jayway.jsonpath.json.JsonException;
import java.util.List; import com.jayway.jsonpath.json.JsonFactory;
import java.util.regex.Pattern; import com.jayway.jsonpath.json.JsonObject;
/**
* Created by IntelliJ IDEA. import java.util.ArrayList;
* User: kallestenflo import java.util.List;
* Date: 2/2/11 import java.util.regex.Pattern;
* Time: 2:33 PM
*/ /**
public class TraverseFilter extends JsonPathFilterBase { * Created by IntelliJ IDEA.
* User: kallestenflo
public final static Pattern PATTERN = Pattern.compile("\\.\\."); * Date: 2/2/11
* Time: 2:33 PM
@Override */
public FilterOutput apply(FilterOutput filter) { public class TraverseFilter extends JsonPathFilterBase {
List<Object> result = new JSONArray();
public final static Pattern PATTERN = Pattern.compile("\\.\\.");
traverse(filter.getResult(), result);
return new FilterOutput(result); public List<JsonElement> apply(JsonElement element) throws JsonException {
} List<JsonElement> result = new ArrayList<JsonElement>();
traverse(element, result);
private void traverse(Object container, List<Object> result) { return result;
}
if (JsonUtil.isMap(container)) {
result.add(container); private void traverse(JsonElement container, List<JsonElement> result) throws JsonException {
for (Object value : JsonUtil.toMap(container).values()) { if (container.isJsonObject()) {
if (JsonUtil.isContainer(value)) { result.add(container);
traverse(value, result);
} for (JsonElement value : container.toJsonObject().getProperties()) {
} if (value.isContainer()) {
} else if (JsonUtil.isList(container)) { traverse(value, result);
}
for (Object value : JsonUtil.toList(container)) { }
if (JsonUtil.isContainer(value)) { } else if (container.isJsonArray()) {
traverse(value, result);
} for (JsonElement value : container.toJsonArray()) {
} if ( value.isContainer()) {
} traverse(value, result);
} }
}
}
}
@Override
public String getPathSegment() throws JsonException {
return null;
}
} }

87
json-path/src/main/java/com/jayway/jsonpath/filter/WildcardPropertyFilter.java

@ -1,39 +1,48 @@
package com.jayway.jsonpath.filter; package com.jayway.jsonpath.filter;
import com.jayway.jsonpath.JsonUtil;
import net.minidev.json.JSONArray; import com.jayway.jsonpath.json.JsonArray;
import com.jayway.jsonpath.json.JsonElement;
import java.util.List; import com.jayway.jsonpath.json.JsonException;
import java.util.regex.Pattern; import com.jayway.jsonpath.json.JsonFactory;
/**
* Created by IntelliJ IDEA. import java.util.ArrayList;
* User: kallestenflo import java.util.List;
* Date: 2/15/11 import java.util.regex.Pattern;
* Time: 8:42 PM
*/ /**
public class WildcardPropertyFilter extends JsonPathFilterBase { * Created by IntelliJ IDEA.
* User: kallestenflo
public final static Pattern PATTERN = Pattern.compile("\\*"); * Date: 2/15/11
* Time: 8:42 PM
*/
@Override public class WildcardPropertyFilter extends JsonPathFilterBase {
public FilterOutput apply(FilterOutput filter) {
public final static Pattern PATTERN = Pattern.compile("\\*");
List<Object> result = new JSONArray(); private JsonFactory factory = com.jayway.jsonpath.json.minidev.MiniJsonFactory.getInstance();
if (filter.isList()) { @Override
for (Object current : filter.getResultAsList()) { public String getPathSegment() throws JsonException {
for (Object value : JsonUtil.toMap(current).values()) { return null;
result.add(value); }
}
} @Override
} else { public List<JsonElement> apply(JsonElement element) throws JsonException {
for (Object value : JsonUtil.toMap(filter.getResult()).values()) { List<JsonElement> result = new ArrayList<JsonElement>();
result.add(value);
} if (element.isJsonArray()) {
} for (JsonElement current : element.toJsonArray()) {
return new FilterOutput(result); for (JsonElement value : current.toJsonObject().getProperties()) {
result.add(value);
} }
} }
} else {
for (JsonElement value : element.toJsonObject().getProperties()){
result.add(value);
}
}
return result;
}
}

130
json-path/src/test/java/com/jayway/jsonpath/ExpressionEvalTest.java

@ -1,65 +1,65 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import com.jayway.jsonpath.eval.ExpressionEvaluator; import com.jayway.jsonpath.eval.ExpressionEvaluator;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
* Created by IntelliJ IDEA. * Created by IntelliJ IDEA.
* User: kallestenflo * User: kallestenflo
* Date: 2/4/11 * Date: 2/4/11
* Time: 9:32 PM * Time: 9:32 PM
*/ */
public class ExpressionEvalTest { public class ExpressionEvalTest {
@Test @Test
public void long_eval() throws Exception { public void long_eval() throws Exception {
assertTrue(ExpressionEvaluator.eval(1L, "=", "1")); assertTrue(ExpressionEvaluator.eval(1L, "=", "1"));
assertTrue(ExpressionEvaluator.eval(2L, "!=", "1")); assertTrue(ExpressionEvaluator.eval(2L, "!=", "1"));
assertTrue(ExpressionEvaluator.eval(2L, ">", "1")); assertTrue(ExpressionEvaluator.eval(2L, ">", "1"));
assertTrue(ExpressionEvaluator.eval(2L, ">=", "1")); assertTrue(ExpressionEvaluator.eval(2L, ">=", "1"));
assertTrue(ExpressionEvaluator.eval(2L, ">=", "2")); assertTrue(ExpressionEvaluator.eval(2L, ">=", "2"));
assertTrue(ExpressionEvaluator.eval(1L, "<", "2")); assertTrue(ExpressionEvaluator.eval(1L, "<", "2"));
assertTrue(ExpressionEvaluator.eval(2L, "<=", "2")); assertTrue(ExpressionEvaluator.eval(2L, "<=", "2"));
assertFalse(ExpressionEvaluator.eval(1, ">", "2")); assertFalse(ExpressionEvaluator.eval(1, ">", "2"));
assertFalse(ExpressionEvaluator.eval(1, ">=", "2")); assertFalse(ExpressionEvaluator.eval(1, ">=", "2"));
assertFalse(ExpressionEvaluator.eval(2, "<", "1")); assertFalse(ExpressionEvaluator.eval(2, "<", "1"));
assertFalse(ExpressionEvaluator.eval(2, "<=", "1")); assertFalse(ExpressionEvaluator.eval(2, "<=", "1"));
assertFalse(ExpressionEvaluator.eval(1, "=", "2")); assertFalse(ExpressionEvaluator.eval(1, "=", "2"));
assertFalse(ExpressionEvaluator.eval(1, "!=", "1")); assertFalse(ExpressionEvaluator.eval(1, "!=", "1"));
} }
@Test @Test
public void double_eval() throws Exception { public void double_eval() throws Exception {
assertTrue(ExpressionEvaluator.eval(1D, "=", "1")); assertTrue(ExpressionEvaluator.eval(1D, "=", "1"));
assertTrue(ExpressionEvaluator.eval(2D, "!=", "1")); assertTrue(ExpressionEvaluator.eval(2D, "!=", "1"));
assertTrue(ExpressionEvaluator.eval(2D, ">", "1")); assertTrue(ExpressionEvaluator.eval(2D, ">", "1"));
assertTrue(ExpressionEvaluator.eval(2D, ">=", "1")); assertTrue(ExpressionEvaluator.eval(2D, ">=", "1"));
assertTrue(ExpressionEvaluator.eval(2D, ">=", "2")); assertTrue(ExpressionEvaluator.eval(2D, ">=", "2"));
assertTrue(ExpressionEvaluator.eval(1D, "<", "2")); assertTrue(ExpressionEvaluator.eval(1D, "<", "2"));
assertTrue(ExpressionEvaluator.eval(2D, "<=", "2")); assertTrue(ExpressionEvaluator.eval(2D, "<=", "2"));
assertFalse(ExpressionEvaluator.eval(1D, ">", "2")); assertFalse(ExpressionEvaluator.eval(1D, ">", "2"));
assertFalse(ExpressionEvaluator.eval(1D, ">=", "2")); assertFalse(ExpressionEvaluator.eval(1D, ">=", "2"));
assertFalse(ExpressionEvaluator.eval(2D, "<", "1")); assertFalse(ExpressionEvaluator.eval(2D, "<", "1"));
assertFalse(ExpressionEvaluator.eval(2D, "<=", "1")); assertFalse(ExpressionEvaluator.eval(2D, "<=", "1"));
assertFalse(ExpressionEvaluator.eval(1D, "=", "2")); assertFalse(ExpressionEvaluator.eval(1D, "=", "2"));
assertFalse(ExpressionEvaluator.eval(1D, "!=", "1")); assertFalse(ExpressionEvaluator.eval(1D, "!=", "1"));
} }
@Test @Test
public void string_eval() throws Exception { public void string_eval() throws Exception {
assertTrue(ExpressionEvaluator.eval("A", "=", "A")); assertTrue(ExpressionEvaluator.eval("A", "=", "A"));
assertTrue(ExpressionEvaluator.eval("B", "!=", "A")); assertTrue(ExpressionEvaluator.eval("B", "!=", "A"));
} }
} }

491
json-path/src/test/java/com/jayway/jsonpath/JsonPathTest.java

@ -1,203 +1,288 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.Before;
import org.junit.Ignore;
import java.util.List; import org.junit.Test;
import java.util.Map;
import com.jayway.jsonpath.json.JsonArray;
import static org.hamcrest.Matchers.equalTo; import com.jayway.jsonpath.json.JsonElement;
import static org.hamcrest.Matchers.hasItems; import com.jayway.jsonpath.json.JsonException;
import static org.junit.Assert.*; import com.jayway.jsonpath.json.JsonFactory;
import com.jayway.jsonpath.json.JsonObject;
/**
* Created by IntelliJ IDEA.
* User: kallestenflo import java.util.ArrayList;
* Date: 2/2/11 import java.util.List;
* Time: 3:07 PM import java.util.Map;
*/
public class JsonPathTest { import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
public final static String ARRAY = "[{\"value\": 1},{\"value\": 2}, {\"value\": 3},{\"value\": 4}]"; import static org.junit.Assert.*;
public final static String DOCUMENT = /**
"{ \"store\": {\n" + * Created by IntelliJ IDEA.
" \"book\": [ \n" + * User: kallestenflo
" { \"category\": \"reference\",\n" + * Date: 2/2/11
" \"author\": \"Nigel Rees\",\n" + * Time: 3:07 PM
" \"title\": \"Sayings of the Century\",\n" + */
" \"price\": 8.95\n" + public abstract class JsonPathTest {
" },\n" +
" { \"category\": \"fiction\",\n" + public final static String ARRAY = "[{\"value\": 1},{\"value\": 2}, {\"value\": 3},{\"value\": 4}]";
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" + public final static String DOCUMENT =
" \"price\": 12.99\n" + "{ \"store\": {\n" +
" },\n" + " \"book\": [ \n" +
" { \"category\": \"fiction\",\n" + " { \"category\": \"reference\",\n" +
" \"author\": \"Herman Melville\",\n" + " \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Moby Dick\",\n" + " \"title\": \"Sayings of the Century\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.95\n" +
" \"price\": 8.99\n" + " },\n" +
" },\n" + " { \"category\": \"fiction\",\n" +
" { \"category\": \"fiction\",\n" + " \"author\": \"Evelyn Waugh\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" + " \"title\": \"Sword of Honour\",\n" +
" \"title\": \"The Lord of the Rings\",\n" + " \"price\": 12.99\n" +
" \"isbn\": \"0-395-19395-8\",\n" + " },\n" +
" \"price\": 22.99\n" + " { \"category\": \"fiction\",\n" +
" }\n" + " \"author\": \"Herman Melville\",\n" +
" ],\n" + " \"title\": \"Moby Dick\",\n" +
" \"bicycle\": {\n" + " \"isbn\": \"0-553-21311-3\",\n" +
" \"color\": \"red\",\n" + " \"price\": 8.99\n" +
" \"price\": 19.95,\n" + " },\n" +
" \"foo:bar\": \"fooBar\"\n" + " { \"category\": \"fiction\",\n" +
" }\n" + " \"author\": \"J. R. R. Tolkien\",\n" +
" }\n" + " \"title\": \"The Lord of the Rings\",\n" +
"}"; " \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99\n" +
" }\n" +
@Test " ],\n" +
public void filter_an_array() throws Exception { " \"bicycle\": {\n" +
List<Object> matches = JsonPath.read(ARRAY, "$.[?(@.value = 1)]"); " \"color\": \"red\",\n" +
" \"price\": 19.95,\n" +
assertEquals(1, matches.size()); " \"foo:bar\": \"fooBar\"\n" +
System.out.println(matches); " }\n" +
} " }\n" +
"}";
@Test
public void read_path_with_colon() throws Exception { @Before
public void init_factory(){
assertEquals(JsonPath.read(DOCUMENT, "$.store.bicycle.foo:bar"), "fooBar");
assertEquals(JsonPath.read(DOCUMENT, "$.['store'].['bicycle'].['foo:bar']"), "fooBar"); }
}
@Test
@Test public void filter_an_array() throws Exception {
public void read_document_from_root() throws Exception { JsonElement matches = JsonPath.read(ARRAY, "$.[?(@.value = 1)]");
Map result = JsonPath.read(DOCUMENT, "$.store"); assertEquals(true, matches.isJsonObject());
System.out.println(matches);
assertEquals(2, result.values().size()); }
@Test
} public void read_path_with_colon() throws Exception {
assertEquals(JsonPath.read(DOCUMENT, "$.store.bicycle.foo:bar").toObject(), "fooBar");
@Test assertEquals(JsonPath.read(DOCUMENT, "$.['store'].['bicycle'].['foo:bar']").toObject(), "fooBar");
public void read_store_book_1() throws Exception { }
JsonPath path = JsonPath.compile("$.store.book[1]");
Map map = path.read(DOCUMENT);
@Test
assertEquals("Evelyn Waugh", map.get("author")); public void parent_ref() throws Exception {
}
@Test String doc = "{foo:{biz:{id:1}}}";
public void read_store_book_wildcard() throws Exception {
JsonPath path = JsonPath.compile("$.store.book[*]");
List<Object> list = path.read(DOCUMENT); assertEquals(JsonPath.read(doc, "$.foo.biz").toString(), "{\"id\":1}");
} JsonElement j = JsonPath.read(doc, "$.foo.biz");
assertEquals(j.getParentReference().getParent().toString() , "{\"biz\":{\"id\":1}}");;
@Test assertEquals(j.getParentReference().getParent().getParentReference().getParent().toString(), "{\"foo\":{\"biz\":{\"id\":1}}}");
public void read_store_book_author() throws Exception {
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[0,1].author"), hasItems("Nigel Rees", "Evelyn Waugh"));
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[*].author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); doc = "{foo:{biz:[{Id:1},{Id:2},{Id:4,foo:1234}]}}";
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.['store'].['book'][*].['author']"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
} JsonElement root = JsonPath.parse(doc);
assertEquals(JsonPath.read(doc, "$.foo.biz.[2].foo").toString(), "1234");
assertEquals(JsonPath.read(doc, "$.foo.biz.[2].foo").getParentReference().getParent().toJsonObject().get("Id").toString(), "4");
@Test
public void all_authors() throws Exception { JsonElement doc_json = JsonFactory.getInstance().parse( "{foo:[[[1],2,3,4],1,2,3]}");
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$..author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); JsonElement je = JsonPath.read(doc_json, "$.foo[0][0]");
} je.getParentReference().setReference( JsonFactory.getInstance().createJsonPrimitive("foo"));
assertEquals(doc_json.toString(),"{\"foo\":[[\"foo\",2,3,4],1,2,3]}");
@Test
public void all_store_properties() throws Exception {
List<Object> itemsInStore = JsonPath.read(DOCUMENT, "$.store.*"); }
assertEquals(JsonPath.read(itemsInStore, "$.[0].[0].author"), "Nigel Rees");
assertEquals(JsonPath.read(itemsInStore, "$.[0][0].author"), "Nigel Rees"); @Test
} public void type_test() throws Exception {
@Test
public void all_prices_in_store() throws Exception { String doc = "{foo:{biz:{id:1}}}";
assertThat(JsonPath.<List<Double>>read(DOCUMENT, "$.store..price"), hasItems(8.95D, 12.99D, 8.99D, 19.95D)); assertEquals(JsonPath.read(doc, "$.foo.biz.(object)").toString(), "{\"id\":1}");
assertEquals(JsonPath.read(doc, "$.foo.biz.(collection)"), null);
}
@Test doc = "{foo:{biz:[{Id:1},{Id:2},{Id:4,foo:1234}]}}";
public void access_array_by_index_from_tail() throws Exception {
JsonElement root = JsonPath.parse(doc);
assertThat(JsonPath.<String>read(DOCUMENT, "$..book[(@.length-1)].author"), equalTo("J. R. R. Tolkien")); assertEquals(JsonPath.read(doc, "$.foo.biz.(collection)[2].foo.(value)").toString(), "1234");
assertThat(JsonPath.<String>read(DOCUMENT, "$..book[-1:].author"), equalTo("J. R. R. Tolkien"));
}
@Test }
public void read_store_book_index_0_and_1() throws Exception {
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[0,1].author"), hasItems("Nigel Rees", "Evelyn Waugh"));
assertTrue(JsonPath.<List>read(DOCUMENT, "$.store.book[0,1].author").size() == 2); @Test
} public void read_document_from_root() throws Exception {
@Test com.jayway.jsonpath.json.JsonObject result = JsonPath.read(DOCUMENT, "$.store").toJsonObject();
public void read_store_book_pull_first_2() throws Exception {
assertEquals(2, result.getProperties().size());
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[:2].author"), hasItems("Nigel Rees", "Evelyn Waugh"));
assertTrue(JsonPath.<List>read(DOCUMENT, "$.store.book[:2].author").size() == 2);
} }
@Test @Test
public void read_store_book_filter_by_isbn() throws Exception { public void read_store_book_1() throws Exception {
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[?(@.isbn)].isbn"), hasItems("0-553-21311-3", "0-395-19395-8")); JsonPath path = JsonPath.compile("$.store.book[1]");
assertTrue(JsonPath.<List>read(DOCUMENT, "$.store.book[?(@.isbn)].isbn").size() == 2);
} JsonElement map = path.read(DOCUMENT);
@Test assertEquals("Evelyn Waugh", map.toJsonObject().get("author").toObject());
public void all_books_cheaper_than_10() throws Exception { }
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[?(@.price < 10)].title"), hasItems("Sayings of the Century", "Moby Dick")); @Test
public void read_store_book_wildcard() throws Exception {
} JsonPath path = JsonPath.compile("$.store.book[*]");
@Test JsonElement list = path.read(DOCUMENT);
public void all_books_with_category_reference() throws Exception {
}
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$..book[?(@.category = 'reference')].title"), hasItems("Sayings of the Century"));
@Test
} public void read_store_book_author() throws Exception {
Iterable<String> l1 = toList(JsonPath.read(DOCUMENT, "$.store.book[0,1].author"));
@Test assertThat(l1, hasItems("Nigel Rees", "Evelyn Waugh"));
public void all_members_of_all_documents() throws Exception {
List<String> all = JsonPath.read(DOCUMENT, "$..*"); Iterable<String> l2 = toList(JsonPath.read(DOCUMENT, "$.store.book[*].author"));
} assertThat(l2, hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
@Test Iterable<String> l3 = toList(JsonPath.read(DOCUMENT, "$.['store'].['book'][*].['author']"));
public void access_index_out_of_bounds_does_not_throw_exception() throws Exception { assertThat(l3, hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
Object res = JsonPath.read(DOCUMENT, "$.store.book[100].author"); }
assertNull(res);
private <T> List<T> toList(JsonElement read) throws JsonException {
res = JsonPath.read(DOCUMENT, "$.store.book[1, 200].author"); List l = new ArrayList<T>();
for(JsonElement e: read.toJsonArray()){
l.add((T) e.toObject());
assertThat((List<String>)res, hasItems("Evelyn Waugh")); }
//assertNull((); return l ;
} }
/* @Test
@Test(expected = InvalidPathException.class) public void all_authors() throws Exception {
public void invalid_space_path_throws_exception() throws Exception { Iterable<String> l1 = toList(JsonPath.read(DOCUMENT, "$..author"));
JsonPath.read(DOCUMENT, "space is not good"); assertThat(l1, hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
} }
*/
@Test(expected = InvalidPathException.class) @Test
public void invalid_new_path_throws_exception() throws Exception { public void all_store_properties() throws Exception {
JsonPath.read(DOCUMENT, "new "); JsonArray itemsInStore = JsonPath.read(DOCUMENT, "$.store.*").toJsonArray();
}
} assertEquals(JsonPath.read(itemsInStore, "$.[0].[0].author").toObject(), "Nigel Rees");
assertEquals(JsonPath.read(itemsInStore, "$.[0][0].author").toObject(), "Nigel Rees");
}
@Test
public void all_prices_in_store() throws Exception {
assertThat(this.<Double>toList(JsonPath.read(DOCUMENT, "$.store..price")), hasItems(8.95D, 12.99D, 8.99D, 19.95D));
}
@Test
public void access_array_by_index_from_tail() throws Exception {
assertThat((String)JsonPath.read(DOCUMENT, "$..book[(@.length-1)].author").toObject(), equalTo("J. R. R. Tolkien"));
assertThat((String)JsonPath.read(DOCUMENT, "$..book[-1:].author").toObject(), equalTo("J. R. R. Tolkien"));
}
@Test
public void read_store_book_index_0_and_1() throws Exception {
assertThat(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[0,1].author")), hasItems("Nigel Rees", "Evelyn Waugh"));
assertTrue(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[0,1].author")).size() == 2);
}
@Test
public void read_store_book_pull_first_2() throws Exception {
assertThat(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[:2].author")), hasItems("Nigel Rees", "Evelyn Waugh"));
assertTrue(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[:2].author")).size() == 2);
}
@Test
public void read_store_book_filter_by_isbn() throws Exception {
assertThat(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[?(@.isbn)].isbn")), hasItems("0-553-21311-3", "0-395-19395-8"));
assertTrue(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[?(@.isbn)].isbn")).size() == 2);
}
@Test
public void all_books_cheaper_than_10() throws Exception {
Object o = JsonPath.read(DOCUMENT, "$.store.book[?(@.price < 10)].title");
assertThat(this.<String>toList(JsonPath.read(DOCUMENT, "$.store.book[?(@.price < 10)].title")), hasItems("Sayings of the Century", "Moby Dick"));
}
@Test
public void all_books_with_category_reference() throws Exception {
Object o = JsonPath.read(DOCUMENT, "$..book[?(@.category = 'reference')].title");
assertEquals(JsonPath.read(DOCUMENT, "$..book[?(@.category = 'reference')].title").toObject(), "Sayings of the Century");
}
@Test
public void all_members_of_all_documents() throws Exception {
JsonPath.read(DOCUMENT, "$..*");
}
@Test
public void access_index_out_of_bounds_does_not_throw_exception() throws Exception {
Object res = JsonPath.read(DOCUMENT, "$.store.book[100].author");
assertNull(res);
JsonElement res2 = JsonPath.read(DOCUMENT, "$.store.book[1, 200].author");
assertEquals(res2.toObject(), "Evelyn Waugh");
//assertNull(();
}
/*
@Test(expected = InvalidPathException.class)
public void invalid_space_path_throws_exception() throws Exception {
JsonPath.read(DOCUMENT, "space is not good");
}
*/
@Test(expected = InvalidPathException.class)
public void invalid_new_path_throws_exception() throws Exception {
JsonPath.read(DOCUMENT, "new ");
}
}

26
json-path/src/test/java/com/jayway/jsonpath/ParserTest.java

@ -1,5 +1,6 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.text.ParseException; import java.text.ParseException;
@ -12,6 +13,7 @@ import static junit.framework.Assert.assertEquals;
* Date: 6/25/11 * Date: 6/25/11
* Time: 4:16 PM * Time: 4:16 PM
*/ */
public class ParserTest { public class ParserTest {
@ -19,33 +21,25 @@ public class ParserTest {
private final static String NO_QUOTE_JSON = "{lhs: 1.0 U.S. dollar, rhs: 6.39778892, error: null, icc: true}"; private final static String NO_QUOTE_JSON = "{lhs: 1.0 U.S. dollar, rhs: 6.39778892, error: null, icc: true}";
@Test @Test
@Ignore
public void default_mode_is_SLACK_MODE() throws Exception { public void default_mode_is_SLACK_MODE() throws Exception {
assertEquals(JsonPath.SLACK_MODE, JsonPath.getMode()); // assertEquals(JsonPath.SLACK_MODE, JsonPath.getMode());
} }
@Test @Test
@Ignore
public void slack_mode_allows_single_quotes() throws Exception { public void slack_mode_allows_single_quotes() throws Exception {
assertEquals(JsonPath.read(SINGLE_QUOTE_JSON, "lhs"), "1.0 U.S. dollar"); assertEquals(JsonPath.read(SINGLE_QUOTE_JSON, "lhs").toPrimitive(), "1.0 U.S. dollar");
assertEquals(JsonPath.read(SINGLE_QUOTE_JSON, "rhs"), 6.39778892D); assertEquals(JsonPath.read(SINGLE_QUOTE_JSON, "rhs").toPrimitive(), 6.39778892D);
} }
@Test @Test
@Ignore
public void slack_mode_allows_no_quotes() throws Exception { public void slack_mode_allows_no_quotes() throws Exception {
assertEquals(JsonPath.read(NO_QUOTE_JSON, "lhs"), "1.0 U.S. dollar"); assertEquals(JsonPath.read(NO_QUOTE_JSON, "lhs").getWrappedElement(), "1.0 U.S. dollar");
assertEquals(JsonPath.read(NO_QUOTE_JSON, "rhs"), 6.39778892D); assertEquals(JsonPath.read(NO_QUOTE_JSON, "rhs").getWrappedElement(), 6.39778892D);
}
@Test(expected = ParseException.class)
public void strict_mode_does_not_accept_single_quotes() throws Exception {
JsonPath.setMode(JsonPath.STRICT_MODE);
JsonPath.read(SINGLE_QUOTE_JSON, "lhs");
} }
@Test(expected = ParseException.class)
public void strict_mode_does_not_accept_no_quotes() throws Exception {
JsonPath.setMode(JsonPath.STRICT_MODE);
JsonPath.read(NO_QUOTE_JSON, "lhs");
}
} }

60
json-path/src/test/java/com/jayway/jsonpath/PathUtilTest.java

@ -1,30 +1,30 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
* Created by IntelliJ IDEA. * Created by IntelliJ IDEA.
* User: kallestenflo * User: kallestenflo
* Date: 2/3/11 * Date: 2/3/11
* Time: 9:58 PM * Time: 9:58 PM
*/ */
public class PathUtilTest { public class PathUtilTest {
@Test @Test
public void wildcard_is_not_definite() throws Exception { public void wildcard_is_not_definite() throws Exception {
assertFalse(PathUtil.isPathDefinite("$..book[0]")); assertFalse(PathUtil.isPathDefinite("$..book[0]"));
} }
@Test @Test
public void is_definite() throws Exception { public void is_definite() throws Exception {
assertTrue(PathUtil.isPathDefinite("$.definite.this.is")); assertTrue(PathUtil.isPathDefinite("$.definite.this.is"));
assertTrue(PathUtil.isPathDefinite("$.definite:this.is")); assertTrue(PathUtil.isPathDefinite("$.definite:this.is"));
assertTrue(PathUtil.isPathDefinite("rows[0].id")); assertTrue(PathUtil.isPathDefinite("rows[0].id"));
} }
} }

138
json-path/src/test/java/com/jayway/jsonpath/SplitPathFragmentsTest.java

@ -1,69 +1,69 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.Matchers.hasItemInArray; import static org.hamcrest.Matchers.hasItemInArray;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
/** /**
* Created by IntelliJ IDEA. * Created by IntelliJ IDEA.
* User: kallestenflo * User: kallestenflo
* Date: 2/2/11 * Date: 2/2/11
* Time: 1:22 PM * Time: 1:22 PM
*/ */
public class SplitPathFragmentsTest { public class SplitPathFragmentsTest {
/* /*
1. "$..book[-1:].foo.bar" 1. "$..book[-1:].foo.bar"
2. "$.store.book[*].author" 2. "$.store.book[*].author"
3. "$..author" 3. "$..author"
4. "$.store.*" 4. "$.store.*"
5. "$.store..price" 5. "$.store..price"
6. "$..book[(@.length-1)]" 6. "$..book[(@.length-1)]"
7. "$..book[-1:] 7. "$..book[-1:]
8. "$..book[0,1]" 8. "$..book[0,1]"
9. "$..book[:2]" 9. "$..book[:2]"
10. "$..book[?(@.isbn)]" 10. "$..book[?(@.isbn)]"
11. "$..book[?(@.price<10)]" 11. "$..book[?(@.price<10)]"
12. "$..*" 12. "$..*"
*/ */
@Test @Test
public void fragments_are_split_correctly() throws Exception { public void fragments_are_split_correctly() throws Exception {
assertThat(PathUtil.splitPath("$..book[-1:].foo.bar"), hasItems("$", "..", "[-1:]", "foo", "bar")); assertThat(PathUtil.splitPath("$..book[-1:].foo.bar"), hasItems("$", "..", "[-1:]", "foo", "bar"));
assertThat(PathUtil.splitPath("$.store.book[*].author"), hasItems("$", "store", "book", "[*]", "author")); assertThat(PathUtil.splitPath("$.store.book[*].author"), hasItems("$", "store", "book", "[*]", "author"));
assertThat(PathUtil.splitPath("$..author"), hasItems("$", "..", "author")); assertThat(PathUtil.splitPath("$..author"), hasItems("$", "..", "author"));
assertThat(PathUtil.splitPath("$.store.*"), hasItems("$", "store", "*")); assertThat(PathUtil.splitPath("$.store.*"), hasItems("$", "store", "*"));
assertThat(PathUtil.splitPath("$.store..price"), hasItems("$", "store", "..", "price")); assertThat(PathUtil.splitPath("$.store..price"), hasItems("$", "store", "..", "price"));
assertThat(PathUtil.splitPath("$..book[(@.length-1)]"), hasItems("$", "..", "book", "[(@.length-1)]")); assertThat(PathUtil.splitPath("$..book[(@.length-1)]"), hasItems("$", "..", "book", "[(@.length-1)]"));
assertThat(PathUtil.splitPath("$..book[-1:]"), hasItems("$", "..", "book", "[-1:]")); assertThat(PathUtil.splitPath("$..book[-1:]"), hasItems("$", "..", "book", "[-1:]"));
assertThat(PathUtil.splitPath("$..book[0,1]"), hasItems("$", "..", "book", "[0,1]")); assertThat(PathUtil.splitPath("$..book[0,1]"), hasItems("$", "..", "book", "[0,1]"));
assertThat(PathUtil.splitPath("$..book[:2]"), hasItems("$", "..", "book", "[:2]")); assertThat(PathUtil.splitPath("$..book[:2]"), hasItems("$", "..", "book", "[:2]"));
assertThat(PathUtil.splitPath("$..book[?(@.isbn)]"), hasItems("$", "..", "book", "[?(@.isbn)]")); assertThat(PathUtil.splitPath("$..book[?(@.isbn)]"), hasItems("$", "..", "book", "[?(@.isbn)]"));
assertThat(PathUtil.splitPath("$..book[?(@.price<10)]"), hasItems("$", "..", "book", "[?(@.price<10)]")); assertThat(PathUtil.splitPath("$..book[?(@.price<10)]"), hasItems("$", "..", "book", "[?(@.price<10)]"));
assertThat(PathUtil.splitPath("$..*"), hasItems("$", "..", "*")); assertThat(PathUtil.splitPath("$..*"), hasItems("$", "..", "*"));
assertThat(PathUtil.splitPath("$.[0][1].author"), hasItems("$", "[0]", "[1]", "author")); assertThat(PathUtil.splitPath("$.[0][1].author"), hasItems("$", "[0]", "[1]", "author"));
assertThat(PathUtil.splitPath("$.[0].[1].author"), hasItems("$", "[0]", "[1]", "author")); assertThat(PathUtil.splitPath("$.[0].[1].author"), hasItems("$", "[0]", "[1]", "author"));
assertThat(PathUtil.splitPath("$.foo:bar.author"), hasItems("$", "foo:bar", "author")); assertThat(PathUtil.splitPath("$.foo:bar.author"), hasItems("$", "foo:bar", "author"));
} }
} }

Loading…
Cancel
Save