Java Code Examples for com.jayway.jsonpath.JsonPath#compile()

The following examples show how to use com.jayway.jsonpath.JsonPath#compile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonPathValidator.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
    try {
        JsonPath.compile(input);
    } catch (final Exception e) {
        return new ValidationResult.Builder()
            .subject(subject)
            .input(input)
            .valid(false)
            .explanation("Invalid JSON Path Expression: " + e.getMessage())
            .build();
    }

    return new ValidationResult.Builder()
        .subject(subject)
        .input(input)
        .valid(true)
        .build();
}
 
Example 2
Source File: JsonPathReader.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void compileJsonPaths(final ConfigurationContext context) {
    this.dateFormat = context.getProperty(DateTimeUtils.DATE_FORMAT).getValue();
    this.timeFormat = context.getProperty(DateTimeUtils.TIME_FORMAT).getValue();
    this.timestampFormat = context.getProperty(DateTimeUtils.TIMESTAMP_FORMAT).getValue();

    final LinkedHashMap<String, JsonPath> compiled = new LinkedHashMap<>();
    for (final PropertyDescriptor descriptor : context.getProperties().keySet()) {
        if (!descriptor.isDynamic()) {
            continue;
        }

        final String fieldName = descriptor.getName();
        final String expression = context.getProperty(descriptor).getValue();
        final JsonPath jsonPath = JsonPath.compile(expression);
        compiled.put(fieldName, jsonPath);
    }

    jsonPaths = compiled;
}
 
Example 3
Source File: JsonEngine.java    From client-encryption-java with MIT License 5 votes vote down vote up
/**
 * Get JSON path to the parent of the object at the given JSON path.
 */
public static String getParentJsonPath(String jsonPathString) {
    JsonPath jsonPath = JsonPath.compile(jsonPathString);
    String compiledPath = jsonPath.getPath();
    Matcher matcher = LAST_ELEMENT_IN_PATH_PATTERN.matcher(compiledPath);
    if (matcher.find()) {
        return compiledPath.replace(matcher.group(1), "");
    }
    throw new IllegalStateException(String.format("Unable to find parent for '%s'", jsonPathString));
}
 
Example 4
Source File: JsonPathFilter.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare(Object configurationObject) {
  if ( configurationObject instanceof Map) {
    Map<String,String> params = ( Map<String,String>) configurationObject;
    pathExpression = params.get("pathExpression");
    jsonPath = JsonPath.compile(pathExpression);
    destNodeName = pathExpression.substring(pathExpression.lastIndexOf(".") + 1);
  }
}
 
Example 5
Source File: JsonPathProvider.java    From bender with Apache License 2.0 5 votes vote down vote up
private static JsonPath getPath(String pathStr) {
  JsonPath path;

  if ((path = CACHE.get(pathStr)) == null) {
    path = JsonPath.compile(pathStr);
    CACHE.put(pathStr, path);
  }

  return path;
}
 
Example 6
Source File: JsonPathBaseEvaluator.java    From nifi with Apache License 2.0 5 votes vote down vote up
static JsonPath compileJsonPathExpression(String exp) {
    try {
        return JsonPath.compile(exp);
    } catch (Exception e) {
        throw new AttributeExpressionLanguageException("Invalid JSON Path expression: " + exp, e);
    }
}
 
Example 7
Source File: JacksonJsonNode.java    From camunda-spin with Apache License 2.0 5 votes vote down vote up
public SpinJsonPathQuery jsonPath(String expression) {
  ensureNotNull("expression", expression);
  try {
    JsonPath query = JsonPath.compile(expression);
    return new JacksonJsonPathQuery(this, query, dataFormat);
  } catch(InvalidPathException pex) {
    throw LOG.unableToCompileJsonPathExpression(expression, pex);
  } catch(IllegalArgumentException aex) {
    throw LOG.unableToCompileJsonPathExpression(expression, aex);
  }
}
 
Example 8
Source File: AbstractJsonPathProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
    String error = null;
    if (isStale(subject, input)) {
        if (JsonPathExpressionValidator.isValidExpression(input)) {
            JsonPath compiledJsonPath = JsonPath.compile(input);
            cacheComputedValue(subject, input, compiledJsonPath);
        } else {
            error = "specified expression was not valid: " + input;
        }
    }
    return new ValidationResult.Builder().subject(subject).valid(error == null).explanation(error).build();
}
 
Example 9
Source File: JsonPathEvaluator.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
static JsonPath compileJsonPathExpression(String exp) {
    try {
        return JsonPath.compile(exp);
    } catch (Exception e) {
        throw new AttributeExpressionLanguageException("Invalid JSON Path expression: " + exp, e);
    }
}
 
Example 10
Source File: FastJsonReader.java    From hop with Apache License 2.0 5 votes vote down vote up
private static JsonPath[] compilePaths( JsonInputField[] fields ) {
  JsonPath[] paths = new JsonPath[ fields.length ];
  int i = 0;
  for ( JsonInputField field : fields ) {
    paths[ i++ ] = JsonPath.compile( field.getPath() );
  }
  return paths;
}
 
Example 11
Source File: JsonUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static JsonPath getValidJsonPath(final String jsonPath) {
    try {
        return JsonPath.compile(jsonPath);
    } catch (IllegalArgumentException iae) {
        throw hammerIllegalArgumentExceptionWithMessage(INVALID_JSONPATH, iae);
    }
}
 
Example 12
Source File: FastJsonReader.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private static JsonPath[] compilePaths( JsonInputField[] fields ) {
  JsonPath[] paths = new JsonPath[ fields.length ];
  int i = 0;
  for ( JsonInputField field : fields ) {
    paths[ i++ ] = JsonPath.compile( field.getPath() );
  }
  return paths;
}
 
Example 13
Source File: JsonEngine.java    From client-encryption-java with MIT License 5 votes vote down vote up
/**
 * Get object key at the given JSON path.
 */
public static String getJsonElementKey(String jsonPathString) {
    JsonPath jsonPath = JsonPath.compile(jsonPathString);
    String compiledPath = jsonPath.getPath();
    Matcher matcher = LAST_ELEMENT_IN_PATH_PATTERN.matcher(compiledPath);
    if (matcher.find()) {
        return matcher.group(1).replace("['", "").replace("']", "");
    }
    throw new IllegalStateException(String.format("Unable to find object key for '%s'", jsonPathString));
}
 
Example 14
Source File: JsonRecordParser.java    From kafka-connect-zeebe with Apache License 2.0 4 votes vote down vote up
public Builder withKeyPath(final String keyPath) {
  this.keyPath = JsonPath.compile(keyPath);
  return this;
}
 
Example 15
Source File: PSQLXyzConnectorIT.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void testModifyFeatures(boolean includeOldStates) throws Exception {
  // =========== INSERT ==========
  String insertJsonFile = "/events/InsertFeaturesEvent.json";
  String insertResponse = invokeLambdaFromFile(insertJsonFile);
  logger.info("RAW RESPONSE: " + insertResponse);
  String insertRequest = IOUtils.toString(GSContext.class.getResourceAsStream(insertJsonFile));
  assertRead(insertRequest, insertResponse, false);
  final JsonPath jsonPathFeatures = JsonPath.compile("$.features");
  List<Map> originalFeatures = jsonPathFeatures.read(insertResponse, jsonPathConf);

  final JsonPath jsonPathFeatureIds = JsonPath.compile("$.features..id");
  List<String> ids = jsonPathFeatureIds.read(insertResponse, jsonPathConf);
  logger.info("Preparation: Inserted features {}", ids);

  // =========== UPDATE ==========
  logger.info("Modify features");
  final DocumentContext updateFeaturesEventDoc = getEventFromResource("/events/InsertFeaturesEvent.json");
  updateFeaturesEventDoc.put("$", "params", Collections.singletonMap("includeOldStates", includeOldStates));

  List<Map> updateFeatures = jsonPathFeatures.read(insertResponse, jsonPathConf);
  updateFeaturesEventDoc.delete("$.insertFeatures");
  updateFeatures.forEach((Map feature) -> {
    final Map<String, Object> properties = (Map<String, Object>) feature.get("properties");
    properties.put("test", "updated");
  });
  updateFeaturesEventDoc.put("$", "updateFeatures", updateFeatures);

  String updateFeaturesEvent = updateFeaturesEventDoc.jsonString();
  String updateFeaturesResponse = invokeLambda(updateFeaturesEvent);
  assertNoErrorInResponse(updateFeaturesResponse);

  List features = jsonPathFeatures.read(updateFeaturesResponse, jsonPathConf);
  assertNotNull("'features' element in ModifyFeaturesResponse is missing", features);
  assertTrue("'features' element in ModifyFeaturesResponse is empty", features.size() > 0);

  final JsonPath jsonPathOldFeatures = JsonPath.compile("$.oldFeatures");
  List oldFeatures = jsonPathOldFeatures.read(updateFeaturesResponse, jsonPathConf);
  if (includeOldStates) {
    assertNotNull("'oldFeatures' element in ModifyFeaturesResponse is missing", oldFeatures);
    assertTrue("'oldFeatures' element in ModifyFeaturesResponse is empty", oldFeatures.size() > 0);
    assertEquals(oldFeatures, originalFeatures);
  } else if (oldFeatures != null) {
    assertEquals("unexpected oldFeatures in ModifyFeaturesResponse", 0, oldFeatures.size());
  }

  // =========== DELETE ==========
  final DocumentContext modifyFeaturesEventDoc = getEventFromResource("/events/InsertFeaturesEvent.json");
  modifyFeaturesEventDoc.put("$", "params", Collections.singletonMap("includeOldStates", includeOldStates));
  modifyFeaturesEventDoc.delete("$.insertFeatures");

  Map<String, String> idsMap = new HashMap<>();
  ids.forEach(id -> idsMap.put(id, null));
  modifyFeaturesEventDoc.put("$", "deleteFeatures", idsMap);

  String deleteEvent = modifyFeaturesEventDoc.jsonString();
  String deleteResponse = invokeLambda(deleteEvent);
  assertNoErrorInResponse(deleteResponse);
  oldFeatures = jsonPathOldFeatures.read(deleteResponse, jsonPathConf);
  if (includeOldStates) {
    assertNotNull("'oldFeatures' element in ModifyFeaturesResponse is missing", oldFeatures);
    assertTrue("'oldFeatures' element in ModifyFeaturesResponse is empty", oldFeatures.size() > 0);
    assertEquals(oldFeatures, features);
  } else if (oldFeatures != null) {
    assertEquals("unexpected oldFeatures in ModifyFeaturesResponse", 0, oldFeatures.size());
  }

  logger.info("Modify features tested successfully");
}
 
Example 16
Source File: JsonRecordParser.java    From kafka-connect-zeebe with Apache License 2.0 4 votes vote down vote up
public Builder withVariablesPath(final String variablesPath) {
  this.variablesPath = JsonPath.compile(variablesPath);
  return this;
}
 
Example 17
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 4 votes vote down vote up
private static Object readJsonElement(DocumentContext context, String jsonPathString) {
    Object payloadJsonObject = context.json();
    JsonPath jsonPath = JsonPath.compile(jsonPathString);
    return jsonPath.read(payloadJsonObject, jsonPathConfig);
}
 
Example 18
Source File: JsonPathSelector.java    From zongtui-webcrawler with GNU General Public License v2.0 4 votes vote down vote up
public JsonPathSelector(String jsonPathStr) {
    this.jsonPathStr = jsonPathStr;
    this.jsonPath = JsonPath.compile(this.jsonPathStr);
}
 
Example 19
Source File: JsonPathExpectationsHelper.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Construct a new {@code JsonPathExpectationsHelper}.
 * @param expression the {@link JsonPath} expression; never {@code null} or empty
 * @param args arguments to parameterize the {@code JsonPath} expression with,
 * using formatting specifiers defined in {@link String#format(String, Object...)}
 */
public JsonPathExpectationsHelper(String expression, Object... args) {
	Assert.hasText(expression, "expression must not be null or empty");
	this.expression = String.format(expression, args);
	this.jsonPath = JsonPath.compile(this.expression);
}
 
Example 20
Source File: JsonPathExpectationsHelper.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Construct a new {@code JsonPathExpectationsHelper}.
 * @param expression the {@link JsonPath} expression; never {@code null} or empty
 * @param args arguments to parameterize the {@code JsonPath} expression with,
 * using formatting specifiers defined in {@link String#format(String, Object...)}
 */
public JsonPathExpectationsHelper(String expression, Object... args) {
	Assert.hasText(expression, "expression must not be null or empty");
	this.expression = String.format(expression, args);
	this.jsonPath = JsonPath.compile(this.expression);
}