
com.crabshue.commons.json.jsonpath.JsonPathEvaluator Maven / Gradle / Ivy
package com.crabshue.commons.json.jsonpath;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.crabshue.commons.exceptions.ApplicationException;
import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.json.jsonpath.exceptions.JsonPathErrorContext;
import com.crabshue.commons.json.jsonpath.exceptions.JsonPathErrorType;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.JsonPathException;
public class JsonPathEvaluator {
private static Logger logger = LoggerFactory.getLogger(JsonPathEvaluator.class);
private DocumentContext jsonObject;
private String jsonPath;
public static JsonPathEvaluator of(final String json) {
Objects.requireNonNull(json);
final JsonPathEvaluator ret = new JsonPathEvaluator();
ret.jsonObject = JsonPath.parse(json);
return ret;
}
public static JsonPathEvaluator of(final InputStream json) {
Objects.requireNonNull(json);
final JsonPathEvaluator ret = new JsonPathEvaluator();
ret.jsonObject = JsonPath.parse(json);
return ret;
}
public static JsonPathEvaluator of(final File json) {
Objects.requireNonNull(json);
final JsonPathEvaluator ret = new JsonPathEvaluator();
try {
ret.jsonObject = JsonPath.parse(json);
} catch (IOException e) {
throw new SystemException(JsonPathErrorType.CANNOT_PARSE_JSON, e)
.addContextValue(JsonPathErrorContext.JSON_FILE, json);
}
return ret;
}
public static JsonPathEvaluator of(final URL json) {
Objects.requireNonNull(json);
final JsonPathEvaluator ret = new JsonPathEvaluator();
try {
ret.jsonObject = JsonPath.parse(json);
} catch (IOException e) {
throw new SystemException(JsonPathErrorType.CANNOT_PARSE_JSON, e)
.addContextValue(JsonPathErrorContext.JSON_URL, json);
}
return ret;
}
public JsonPathEvaluator withJsonPath(final String jsonPath) {
Objects.requireNonNull(jsonPath);
this.jsonPath = jsonPath;
return this;
}
public T evaluate() {
try {
final T ret = this.jsonObject.read(this.jsonPath);
logger.info("Json path evaluated [{}] : [{}]", this.jsonPath, ret);
return ret;
} catch (JsonPathException e) {
throw new ApplicationException(JsonPathErrorType.CANNOT_EVALUATE_JSON_PATH, e)
.addContextValue(JsonPathErrorContext.JSON, jsonObject)
.addContextValue(JsonPathErrorContext.JSON_PATH, this.jsonPath);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy