Search in sources :

Example 1 with InvalidJsonException

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();
    }
}
Also used : StringWriter(java.io.StringWriter) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) IOException(java.io.IOException)

Example 2 with 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);
    }
}
Also used : InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 3 with InvalidJsonException

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() });
}
Also used : StandardValidators(org.apache.nifi.processor.util.StandardValidators) FRAGMENT_INDEX(org.apache.nifi.flowfile.attributes.FragmentAttributes.FRAGMENT_INDEX) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) ValidationContext(org.apache.nifi.components.ValidationContext) HashMap(java.util.HashMap) EventDriven(org.apache.nifi.annotation.behavior.EventDriven) SystemResource(org.apache.nifi.annotation.behavior.SystemResource) ComponentLog(org.apache.nifi.logging.ComponentLog) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils(org.apache.commons.lang3.StringUtils) SideEffectFree(org.apache.nifi.annotation.behavior.SideEffectFree) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ArrayList(java.util.ArrayList) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) HashSet(java.util.HashSet) FRAGMENT_COUNT(org.apache.nifi.flowfile.attributes.FragmentAttributes.FRAGMENT_COUNT) WritesAttributes(org.apache.nifi.annotation.behavior.WritesAttributes) Relationship(org.apache.nifi.processor.Relationship) Map(java.util.Map) Requirement(org.apache.nifi.annotation.behavior.InputRequirement.Requirement) FragmentAttributes.copyAttributesToOriginal(org.apache.nifi.flowfile.attributes.FragmentAttributes.copyAttributesToOriginal) ValidationResult(org.apache.nifi.components.ValidationResult) FlowFile(org.apache.nifi.flowfile.FlowFile) FRAGMENT_ID(org.apache.nifi.flowfile.attributes.FragmentAttributes.FRAGMENT_ID) Collection(java.util.Collection) ProcessContext(org.apache.nifi.processor.ProcessContext) Set(java.util.Set) ProcessSession(org.apache.nifi.processor.ProcessSession) UUID(java.util.UUID) WritesAttribute(org.apache.nifi.annotation.behavior.WritesAttribute) SEGMENT_ORIGINAL_FILENAME(org.apache.nifi.flowfile.attributes.FragmentAttributes.SEGMENT_ORIGINAL_FILENAME) JsonPath(com.jayway.jsonpath.JsonPath) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) OnScheduled(org.apache.nifi.annotation.lifecycle.OnScheduled) SupportsBatching(org.apache.nifi.annotation.behavior.SupportsBatching) DocumentContext(com.jayway.jsonpath.DocumentContext) SystemResourceConsideration(org.apache.nifi.annotation.behavior.SystemResourceConsideration) Tags(org.apache.nifi.annotation.documentation.Tags) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) CoreAttributes(org.apache.nifi.flowfile.attributes.CoreAttributes) Collections(java.util.Collections) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) FlowFile(org.apache.nifi.flowfile.FlowFile) HashMap(java.util.HashMap) JsonPath(com.jayway.jsonpath.JsonPath) ComponentLog(org.apache.nifi.logging.ComponentLog) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) ArrayList(java.util.ArrayList) List(java.util.List) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) DocumentContext(com.jayway.jsonpath.DocumentContext)

Example 4 with InvalidJsonException

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);
    }
}
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 5 with InvalidJsonException

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);
    }
}
Also used : CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) OnRemoved(org.apache.nifi.annotation.lifecycle.OnRemoved) ValidationContext(org.apache.nifi.components.ValidationContext) HashMap(java.util.HashMap) EventDriven(org.apache.nifi.annotation.behavior.EventDriven) ComponentLog(org.apache.nifi.logging.ComponentLog) StringUtils(org.apache.commons.lang3.StringUtils) SideEffectFree(org.apache.nifi.annotation.behavior.SideEffectFree) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ProcessException(org.apache.nifi.processor.exception.ProcessException) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) HashSet(java.util.HashSet) Relationship(org.apache.nifi.processor.Relationship) Map(java.util.Map) Requirement(org.apache.nifi.annotation.behavior.InputRequirement.Requirement) ValidationResult(org.apache.nifi.components.ValidationResult) OutputStream(java.io.OutputStream) OnUnscheduled(org.apache.nifi.annotation.lifecycle.OnUnscheduled) FlowFile(org.apache.nifi.flowfile.FlowFile) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ProcessContext(org.apache.nifi.processor.ProcessContext) Set(java.util.Set) ProcessSession(org.apache.nifi.processor.ProcessSession) JsonPath(com.jayway.jsonpath.JsonPath) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) OnScheduled(org.apache.nifi.annotation.lifecycle.OnScheduled) DynamicProperty(org.apache.nifi.annotation.behavior.DynamicProperty) SupportsBatching(org.apache.nifi.annotation.behavior.SupportsBatching) DocumentContext(com.jayway.jsonpath.DocumentContext) Queue(java.util.Queue) Tags(org.apache.nifi.annotation.documentation.Tags) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) Collections(java.util.Collections) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) FlowFile(org.apache.nifi.flowfile.FlowFile) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) JsonPath(com.jayway.jsonpath.JsonPath) ComponentLog(org.apache.nifi.logging.ComponentLog) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) DocumentContext(com.jayway.jsonpath.DocumentContext) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

InvalidJsonException (com.jayway.jsonpath.InvalidJsonException)8 IOException (java.io.IOException)4 DocumentContext (com.jayway.jsonpath.DocumentContext)3 JsonPath (com.jayway.jsonpath.JsonPath)3 PathNotFoundException (com.jayway.jsonpath.PathNotFoundException)3 List (java.util.List)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 StringWriter (java.io.StringWriter)2 StandardCharsets (java.nio.charset.StandardCharsets)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Set (java.util.Set)2 StringUtils (org.apache.commons.lang3.StringUtils)2 EventDriven (org.apache.nifi.annotation.behavior.EventDriven)2 InputRequirement (org.apache.nifi.annotation.behavior.InputRequirement)2