use of com.jayway.jsonpath.InvalidJsonException in project JsonPath by jayway.
the class JacksonJsonProvider method toJson.
@Override
public String toJson(Object obj) {
StringWriter writer = new StringWriter();
try {
JsonGenerator generator = objectMapper.getFactory().createGenerator(writer);
objectMapper.writeValue(generator, obj);
writer.flush();
writer.close();
generator.close();
return writer.getBuffer().toString();
} catch (IOException e) {
throw new InvalidJsonException();
}
}
use of com.jayway.jsonpath.InvalidJsonException in project JsonPath by jayway.
the class JettisonProvider method parse.
@Override
public Object parse(InputStream jsonStream, String charset) throws InvalidJsonException {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int size;
while ((size = jsonStream.read(buffer)) > 0) {
stream.write(buffer, 0, size);
}
return parse(new JettisonTokener(new String(stream.toByteArray(), charset)));
} catch (IOException ioe) {
throw new InvalidJsonException(ioe);
}
}
use of com.jayway.jsonpath.InvalidJsonException in project nifi by apache.
the class SplitJson method onTrigger.
@Override
public void onTrigger(final ProcessContext processContext, final ProcessSession processSession) {
FlowFile original = processSession.get();
if (original == null) {
return;
}
final ComponentLog logger = getLogger();
DocumentContext documentContext;
try {
documentContext = validateAndEstablishJsonContext(processSession, original);
} catch (InvalidJsonException e) {
logger.error("FlowFile {} did not have valid JSON content.", new Object[] { original });
processSession.transfer(original, REL_FAILURE);
return;
}
final JsonPath jsonPath = JSON_PATH_REF.get();
Object jsonPathResult;
try {
jsonPathResult = documentContext.read(jsonPath);
} catch (PathNotFoundException e) {
logger.warn("JsonPath {} could not be found for FlowFile {}", new Object[] { jsonPath.getPath(), original });
processSession.transfer(original, REL_FAILURE);
return;
}
if (!(jsonPathResult instanceof List)) {
logger.error("The evaluated value {} of {} was not a JSON Array compatible type and cannot be split.", new Object[] { jsonPathResult, jsonPath.getPath() });
processSession.transfer(original, REL_FAILURE);
return;
}
List resultList = (List) jsonPathResult;
Map<String, String> attributes = new HashMap<>();
final String fragmentId = UUID.randomUUID().toString();
attributes.put(FRAGMENT_ID.key(), fragmentId);
attributes.put(FRAGMENT_COUNT.key(), Integer.toString(resultList.size()));
for (int i = 0; i < resultList.size(); i++) {
Object resultSegment = resultList.get(i);
FlowFile split = processSession.create(original);
split = processSession.write(split, (out) -> {
String resultSegmentContent = getResultRepresentation(resultSegment, nullDefaultValue);
out.write(resultSegmentContent.getBytes(StandardCharsets.UTF_8));
});
attributes.put(SEGMENT_ORIGINAL_FILENAME.key(), split.getAttribute(CoreAttributes.FILENAME.key()));
attributes.put(FRAGMENT_INDEX.key(), Integer.toString(i));
processSession.transfer(processSession.putAllAttributes(split, attributes), REL_SPLIT);
}
original = copyAttributesToOriginal(processSession, original, fragmentId, resultList.size());
processSession.transfer(original, REL_ORIGINAL);
logger.info("Split {} into {} FlowFiles", new Object[] { original, resultList.size() });
}
use of com.jayway.jsonpath.InvalidJsonException 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);
}
}
use of com.jayway.jsonpath.InvalidJsonException 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);
}
}
Aggregations