use of com.jayway.jsonpath.DocumentContext in project nifi by apache.
the class EvaluateJsonPath method onTrigger.
@Override
public void onTrigger(final ProcessContext processContext, final ProcessSession processSession) throws ProcessException {
FlowFile flowFile = processSession.get();
if (flowFile == null) {
return;
}
final ComponentLog logger = getLogger();
DocumentContext documentContext;
try {
documentContext = validateAndEstablishJsonContext(processSession, flowFile);
} catch (InvalidJsonException e) {
logger.error("FlowFile {} did not have valid JSON content.", new Object[] { flowFile });
processSession.transfer(flowFile, REL_FAILURE);
return;
}
Set<Map.Entry<String, JsonPath>> attributeJsonPathEntries = attributeToJsonPathEntrySetQueue.poll();
if (attributeJsonPathEntries == null) {
attributeJsonPathEntries = processContext.getProperties().entrySet().stream().filter(e -> e.getKey().isDynamic()).collect(Collectors.toMap(e -> e.getKey().getName(), e -> JsonPath.compile(e.getValue()))).entrySet();
}
try {
// We'll only be using this map if destinationIsAttribute == true
final Map<String, String> jsonPathResults = destinationIsAttribute ? new HashMap<>(attributeJsonPathEntries.size()) : Collections.EMPTY_MAP;
for (final Map.Entry<String, JsonPath> attributeJsonPathEntry : attributeJsonPathEntries) {
final String jsonPathAttrKey = attributeJsonPathEntry.getKey();
final JsonPath jsonPathExp = attributeJsonPathEntry.getValue();
Object result;
try {
Object potentialResult = documentContext.read(jsonPathExp);
if (returnType.equals(RETURN_TYPE_SCALAR) && !isJsonScalar(potentialResult)) {
logger.error("Unable to return a scalar value for the expression {} for FlowFile {}. Evaluated value was {}. Transferring to {}.", new Object[] { jsonPathExp.getPath(), flowFile.getId(), potentialResult.toString(), REL_FAILURE.getName() });
processSession.transfer(flowFile, REL_FAILURE);
return;
}
result = potentialResult;
} catch (PathNotFoundException e) {
if (pathNotFound.equals(PATH_NOT_FOUND_WARN)) {
logger.warn("FlowFile {} could not find path {} for attribute key {}.", new Object[] { flowFile.getId(), jsonPathExp.getPath(), jsonPathAttrKey }, e);
}
if (destinationIsAttribute) {
jsonPathResults.put(jsonPathAttrKey, StringUtils.EMPTY);
continue;
} else {
processSession.transfer(flowFile, REL_NO_MATCH);
return;
}
}
final String resultRepresentation = getResultRepresentation(result, nullDefaultValue);
if (destinationIsAttribute) {
jsonPathResults.put(jsonPathAttrKey, resultRepresentation);
} else {
flowFile = processSession.write(flowFile, out -> {
try (OutputStream outputStream = new BufferedOutputStream(out)) {
outputStream.write(resultRepresentation.getBytes(StandardCharsets.UTF_8));
}
});
processSession.getProvenanceReporter().modifyContent(flowFile, "Replaced content with result of expression " + jsonPathExp.getPath());
}
}
// jsonPathResults map will be empty if this is false
if (destinationIsAttribute) {
flowFile = processSession.putAllAttributes(flowFile, jsonPathResults);
}
processSession.transfer(flowFile, REL_MATCH);
} finally {
attributeToJsonPathEntrySetQueue.offer(attributeJsonPathEntries);
}
}
use of com.jayway.jsonpath.DocumentContext in project nifi by apache.
the class JsonPathEvaluator method evaluate.
@Override
public QueryResult<String> evaluate(final Map<String, String> attributes) {
final String subjectValue = subject.evaluate(attributes).getValue();
if (subjectValue == null || subjectValue.length() == 0) {
throw new AttributeExpressionLanguageException("Subject is empty");
}
DocumentContext documentContext = null;
try {
documentContext = validateAndEstablishJsonContext(subjectValue);
} catch (InvalidJsonException e) {
throw new AttributeExpressionLanguageException("Subject contains invalid JSON: " + subjectValue, e);
}
final JsonPath compiledJsonPath;
if (precompiledJsonPathExp != null) {
compiledJsonPath = precompiledJsonPathExp;
} else {
compiledJsonPath = compileJsonPathExpression(jsonPathExp.evaluate(attributes).getValue());
}
Object result = null;
try {
result = documentContext.read(compiledJsonPath);
} catch (Exception e) {
// assume the path did not match anything in the document
return EMPTY_RESULT;
}
return new StringQueryResult(getResultRepresentation(result, EMPTY_RESULT.getValue()));
}
use of com.jayway.jsonpath.DocumentContext in project nifi by apache.
the class JsonPathRowRecordReader method convertJsonNodeToRecord.
@Override
protected Record convertJsonNodeToRecord(final JsonNode jsonNode, final RecordSchema schema, final boolean coerceTypes, final boolean dropUnknownFields) throws IOException {
if (jsonNode == null) {
return null;
}
final DocumentContext ctx = JsonPath.using(STRICT_PROVIDER_CONFIGURATION).parse(jsonNode.toString());
final Map<String, Object> values = new HashMap<>(schema.getFieldCount());
for (final Map.Entry<String, JsonPath> entry : jsonPaths.entrySet()) {
final String fieldName = entry.getKey();
final DataType desiredType = schema.getDataType(fieldName).orElse(null);
if (desiredType == null && dropUnknownFields) {
continue;
}
final JsonPath jsonPath = entry.getValue();
Object value;
try {
value = ctx.read(jsonPath);
} catch (final PathNotFoundException pnfe) {
logger.debug("Evaluated JSONPath Expression {} but the path was not found; will use a null value", new Object[] { entry.getValue() });
value = null;
}
final Optional<RecordField> field = schema.getField(fieldName);
final Object defaultValue = field.isPresent() ? field.get().getDefaultValue() : null;
if (coerceTypes && desiredType != null) {
value = convert(value, desiredType, fieldName, defaultValue);
} else {
final DataType dataType = field.isPresent() ? field.get().getDataType() : null;
value = convert(value, dataType);
}
values.put(fieldName, value);
}
return new MapRecord(schema, values);
}
use of com.jayway.jsonpath.DocumentContext in project vft-capture by videofirst.
the class CaptureControllerTest method shouldStartMinParamsWithNoRecord.
// ===========================================
// [ /api/captures/start ] POST
// ===========================================
@Test
public void shouldStartMinParamsWithNoRecord() throws JSONException {
ResponseEntity<String> response = startVideo(CAPTURE_START_PARAMS_MIN_NO_RECORD);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
String expectedJson = "{" + " 'state': 'started'," + " 'categories': {" + " 'organisation': 'Acme'," + " 'product': 'Moon Rocket'," + " 'module': 'UI'" + " }," + " 'feature': 'Bob Feature'," + " 'scenario': 'Dave Scenario'" + "}";
JSONAssert.assertEquals(expectedJson, response.getBody(), false);
DocumentContext json = JsonPath.parse(response.getBody());
Map<String, String> environmentMap = json.read("$.environment");
assertThat(environmentMap.get("java.awt.graphicsenv")).isNotEmpty();
}
use of com.jayway.jsonpath.DocumentContext in project vft-capture by videofirst.
the class CaptureControllerTest method shouldGetsStatusWithStartedUsingMinParamsAndNoRecord.
// ===========================================
// [ /api/captures/status ] GET
// ===========================================
@Test
public void shouldGetsStatusWithStartedUsingMinParamsAndNoRecord() throws JSONException {
startVideo(CAPTURE_START_PARAMS_MIN_NO_RECORD);
ResponseEntity<String> response = statusVideo();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
String expectedJson = "{" + " 'state': 'started'," + " 'categories': {" + " 'organisation': 'Acme'," + " 'product': 'Moon Rocket'," + " 'module': 'UI'" + " }," + " 'feature': 'Bob Feature'," + " 'scenario': 'Dave Scenario'" + "}";
JSONAssert.assertEquals(expectedJson, response.getBody(), false);
DocumentContext json = JsonPath.parse(response.getBody());
Map<String, String> environmentMap = json.read("$.environment");
assertThat(environmentMap.get("java.awt.graphicsenv")).isNotEmpty();
}
Aggregations