Search in sources :

Example 1 with InvalidPathException

use of com.jayway.jsonpath.InvalidPathException in project intellij-community by JetBrains.

the class JsonPathResponseHandler method lazyCompile.

@NotNull
private JsonPath lazyCompile(@NotNull String path) throws Exception {
    JsonPath jsonPath = myCompiledCache.get(path);
    if (jsonPath == null) {
        try {
            jsonPath = JsonPath.compile(path);
            myCompiledCache.put(path, jsonPath);
        } catch (InvalidPathException e) {
            throw new Exception(String.format("Malformed JsonPath expression '%s'", path));
        }
    }
    return jsonPath;
}
Also used : JsonPath(com.jayway.jsonpath.JsonPath) InvalidPathException(com.jayway.jsonpath.InvalidPathException) InvalidPathException(com.jayway.jsonpath.InvalidPathException) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with InvalidPathException

use of com.jayway.jsonpath.InvalidPathException in project smarthome by eclipse.

the class JSonPathTransformationService method transform.

/**
 * Transforms the input <code>source</code> by JSonPath expression.
 *
 * @param function JsonPath expression
 * @param source String which contains JSON
 * @throws TransformationException If the JsonPath expression is invalid, a {@link InvalidPathException} is thrown,
 *             which is encapsulated in a {@link TransformationException}.
 */
@Override
public String transform(String jsonPathExpression, String source) throws TransformationException {
    if (jsonPathExpression == null || source == null) {
        throw new TransformationException("the given parameters 'JSonPath' and 'source' must not be null");
    }
    logger.debug("about to transform '{}' by the function '{}'", source, jsonPathExpression);
    try {
        Object transformationResult = JsonPath.read(source, jsonPathExpression);
        logger.debug("transformation resulted in '{}'", transformationResult);
        if (transformationResult == null) {
            return UnDefType.NULL.toFullString();
        } else if (transformationResult instanceof List) {
            return flattenList((List<?>) transformationResult);
        } else {
            return transformationResult.toString();
        }
    } catch (PathNotFoundException e) {
        throw new TransformationException("Invalid path '" + jsonPathExpression + "' in '" + source + "'");
    } catch (InvalidPathException | InvalidJsonException e) {
        throw new TransformationException("An error occurred while transforming JSON expression.", e);
    }
}
Also used : TransformationException(org.eclipse.smarthome.core.transform.TransformationException) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) List(java.util.List) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) InvalidPathException(com.jayway.jsonpath.InvalidPathException)

Example 3 with InvalidPathException

use of com.jayway.jsonpath.InvalidPathException in project pentaho-kettle by pentaho.

the class JsonInputTest method testJsonInputPathResolutionSuccess.

@Test
public void testJsonInputPathResolutionSuccess() {
    JsonInputField inputField = new JsonInputField("value");
    final String PATH = "${PARAM_PATH}.price";
    inputField.setPath(PATH);
    inputField.setType(ValueMetaInterface.TYPE_STRING);
    final JsonInputMeta inputMeta = createSimpleMeta("json", inputField);
    VariableSpace variables = new Variables();
    JsonInput jsonInput = null;
    try {
        jsonInput = createJsonInput("json", inputMeta, variables, new Object[] { getBasicTestJson() });
        fail("Without the parameter, this call should fail with an InvalidPathException. If it does not, test fails.");
    } catch (InvalidPathException pathException) {
        assertNull(jsonInput);
    }
    variables.setVariable("PARAM_PATH", "$..book.[*]");
    try {
        jsonInput = createJsonInput("json", inputMeta, variables, new Object[] { getBasicTestJson() });
        assertNotNull(jsonInput);
    } catch (Exception ex) {
        fail("Json Input should be able to resolve the paths with the parameter introduced in the variable space.");
    }
}
Also used : Variables(org.pentaho.di.core.variables.Variables) VariableSpace(org.pentaho.di.core.variables.VariableSpace) FileObject(org.apache.commons.vfs2.FileObject) ValueMetaString(org.pentaho.di.core.row.value.ValueMetaString) InvalidPathException(com.jayway.jsonpath.InvalidPathException) KettleFileException(org.pentaho.di.core.exception.KettleFileException) FileSystemException(org.apache.commons.vfs2.FileSystemException) KettleStepException(org.pentaho.di.core.exception.KettleStepException) KettleException(org.pentaho.di.core.exception.KettleException) InvalidPathException(com.jayway.jsonpath.InvalidPathException) Test(org.junit.Test)

Example 4 with InvalidPathException

use of com.jayway.jsonpath.InvalidPathException in project JsonPath by json-path.

the class PathCompiler method parseFunctionParameters.

/**
 * Parse the parameters of a function call, either the caller has supplied JSON data, or the caller has supplied
 * another path expression which must be evaluated and in turn invoked against the root document.  In this tokenizer
 * we're only concerned with parsing the path thus the output of this function is a list of parameters with the Path
 * set if the parameter is an expression.  If the parameter is a JSON document then the value of the cachedValue is
 * set on the object.
 *
 * Sequence for parsing out the parameters:
 *
 * This code has its own tokenizer - it does some rudimentary level of lexing in that it can distinguish between JSON block parameters
 * and sub-JSON blocks - it effectively regex's out the parameters into string blocks that can then be passed along to the appropriate parser.
 * Since sub-jsonpath expressions can themselves contain other function calls this routine needs to be sensitive to token counting to
 * determine the boundaries.  Since the Path parser isn't aware of JSON processing this uber routine is needed.
 *
 * Parameters are separated by COMMAs ','
 *
 * <pre>
 * doc = {"numbers": [1,2,3,4,5,6,7,8,9,10]}
 *
 * $.sum({10}, $.numbers.avg())
 * </pre>
 *
 * The above is a valid function call, we're first summing 10 + avg of 1...10 (5.5) so the total should be 15.5
 *
 * @return
 *      An ordered list of parameters that are to processed via the function.  Typically functions either process
 *      an array of values and/or can consume parameters in addition to the values provided from the consumption of
 *      an array.
 */
private List<Parameter> parseFunctionParameters(String funcName) {
    ParamType type = null;
    // Parenthesis starts at 1 since we're marking the start of a function call, the close paren will denote the
    // last parameter boundary
    Integer groupParen = 1, groupBracket = 0, groupBrace = 0, groupQuote = 0;
    Boolean endOfStream = false;
    char priorChar = 0;
    List<Parameter> parameters = new ArrayList<Parameter>();
    StringBuffer parameter = new StringBuffer();
    while (path.inBounds() && !endOfStream) {
        char c = path.currentChar();
        path.incrementPosition(1);
        // we're at the start of the stream, and don't know what type of parameter we have
        if (type == null) {
            if (isWhitespace(c)) {
                continue;
            }
            if (c == OPEN_BRACE || isDigit(c) || DOUBLE_QUOTE == c) {
                type = ParamType.JSON;
            } else if (isPathContext(c)) {
                // read until we reach a terminating comma and we've reset grouping to zero
                type = ParamType.PATH;
            }
        }
        switch(c) {
            case DOUBLE_QUOTE:
                if (priorChar != '\\' && groupQuote > 0) {
                    if (groupQuote == 0) {
                        throw new InvalidPathException("Unexpected quote '\"' at character position: " + path.position());
                    }
                    groupQuote--;
                } else {
                    groupQuote++;
                }
                break;
            case OPEN_PARENTHESIS:
                groupParen++;
                break;
            case OPEN_BRACE:
                groupBrace++;
                break;
            case OPEN_SQUARE_BRACKET:
                groupBracket++;
                break;
            case CLOSE_BRACE:
                if (0 == groupBrace) {
                    throw new InvalidPathException("Unexpected close brace '}' at character position: " + path.position());
                }
                groupBrace--;
                break;
            case CLOSE_SQUARE_BRACKET:
                if (0 == groupBracket) {
                    throw new InvalidPathException("Unexpected close bracket ']' at character position: " + path.position());
                }
                groupBracket--;
                break;
            // we've encountered a COMMA do the same
            case CLOSE_PARENTHESIS:
                groupParen--;
                if (0 != groupParen) {
                    parameter.append(c);
                }
            case COMMA:
                // to the parser
                if ((0 == groupQuote && 0 == groupBrace && 0 == groupBracket && ((0 == groupParen && CLOSE_PARENTHESIS == c) || 1 == groupParen))) {
                    endOfStream = (0 == groupParen);
                    if (null != type) {
                        Parameter param = null;
                        switch(type) {
                            case JSON:
                                // parse the json and set the value
                                param = new Parameter(parameter.toString());
                                break;
                            case PATH:
                                LinkedList<Predicate> predicates = new LinkedList<Predicate>();
                                PathCompiler compiler = new PathCompiler(parameter.toString(), predicates);
                                param = new Parameter(compiler.compile());
                                break;
                        }
                        if (null != param) {
                            parameters.add(param);
                        }
                        parameter.delete(0, parameter.length());
                        type = null;
                    }
                }
                break;
        }
        if (type != null && !(c == COMMA && 0 == groupBrace && 0 == groupBracket && 1 == groupParen)) {
            parameter.append(c);
        }
        priorChar = c;
    }
    if (0 != groupBrace || 0 != groupParen || 0 != groupBracket) {
        throw new InvalidPathException("Arguments to function: '" + funcName + "' are not closed properly.");
    }
    return parameters;
}
Also used : ArrayList(java.util.ArrayList) ParamType(com.jayway.jsonpath.internal.function.ParamType) InvalidPathException(com.jayway.jsonpath.InvalidPathException) LinkedList(java.util.LinkedList) Predicate(com.jayway.jsonpath.Predicate) Parameter(com.jayway.jsonpath.internal.function.Parameter)

Example 5 with InvalidPathException

use of com.jayway.jsonpath.InvalidPathException in project JsonPath by json-path.

the class PathCompiler method compile.

public static Path compile(String path, final Predicate... filters) {
    try {
        CharacterIndex ci = new CharacterIndex(path);
        ci.trim();
        if (!(ci.charAt(0) == DOC_CONTEXT) && !(ci.charAt(0) == EVAL_CONTEXT)) {
            ci = new CharacterIndex("$." + path);
            ci.trim();
        }
        if (ci.lastCharIs('.')) {
            fail("Path must not end with a '.' or '..'");
        }
        LinkedList<Predicate> filterStack = new LinkedList<Predicate>(asList(filters));
        Path p = new PathCompiler(ci, filterStack).compile();
        return p;
    } catch (Exception e) {
        InvalidPathException ipe;
        if (e instanceof InvalidPathException) {
            ipe = (InvalidPathException) e;
        } else {
            ipe = new InvalidPathException(e);
        }
        throw ipe;
    }
}
Also used : Path(com.jayway.jsonpath.internal.Path) LinkedList(java.util.LinkedList) InvalidPathException(com.jayway.jsonpath.InvalidPathException) InvalidPathException(com.jayway.jsonpath.InvalidPathException) CharacterIndex(com.jayway.jsonpath.internal.CharacterIndex) Predicate(com.jayway.jsonpath.Predicate)

Aggregations

InvalidPathException (com.jayway.jsonpath.InvalidPathException)13 Predicate (com.jayway.jsonpath.Predicate)4 LinkedList (java.util.LinkedList)4 ArrayList (java.util.ArrayList)3 JsonPath (com.jayway.jsonpath.JsonPath)2 CharacterIndex (com.jayway.jsonpath.internal.CharacterIndex)2 ParamType (com.jayway.jsonpath.internal.function.ParamType)2 Parameter (com.jayway.jsonpath.internal.function.Parameter)2 List (java.util.List)2 FileObject (org.apache.commons.vfs2.FileObject)2 Test (org.junit.Test)2 ValueMetaString (org.pentaho.di.core.row.value.ValueMetaString)2 VariableSpace (org.pentaho.di.core.variables.VariableSpace)2 Variables (org.pentaho.di.core.variables.Variables)2 InvalidJsonException (com.jayway.jsonpath.InvalidJsonException)1 PathNotFoundException (com.jayway.jsonpath.PathNotFoundException)1 Path (com.jayway.jsonpath.internal.Path)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 JSONArray (net.minidev.json.JSONArray)1 FileSystemException (org.apache.commons.vfs2.FileSystemException)1