com.jayway.jsonpath.InvalidJsonException Java Examples

The following examples show how to use com.jayway.jsonpath.InvalidJsonException. 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: JsonResponseValidationSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
private boolean isJsonElementSearchCompleted(HttpResponse response, String jsonPath)
{
    if (response == null)
    {
        return true;
    }
    String responseBody = response.getResponseBodyAsString();
    try
    {
        // Empty response may be in case of HTTP "204 NO CONTENT"
        return StringUtils.isNotEmpty(responseBody) && getElementsNumber(responseBody, jsonPath) > 0;
    }
    catch (InvalidJsonException ignored)
    {
        return false;
    }
}
 
Example #2
Source File: AbstractJsonPathProcessor.java    From nifi with Apache License 2.0 6 votes vote down vote up
static DocumentContext validateAndEstablishJsonContext(ProcessSession processSession, FlowFile flowFile) {
    // Parse the document once into an associated context to support multiple path evaluations if specified
    final AtomicReference<DocumentContext> contextHolder = new AtomicReference<>(null);
    processSession.read(flowFile, new InputStreamCallback() {
        @Override
        public void process(InputStream in) throws IOException {
            try (BufferedInputStream bufferedInputStream = new BufferedInputStream(in)) {
                DocumentContext ctx = JsonPath.using(STRICT_PROVIDER_CONFIGURATION).parse(bufferedInputStream);
                contextHolder.set(ctx);
            } catch (IllegalArgumentException iae) {
                // The JsonPath.parse() above first parses the json, then creates a context object from the parsed
                // json.  It is possible for the json parsing to complete without error, but produce a null object.
                // In this case the context creation will fail and throw an IllegalArgumentException.  This is in
                // my opinion a bug in the JsonPath library, as it doesn't really throw the correct exception
                // contextually.
                // The general handling in derived classes handles InvalidJsonException.
                // The best thing to do here, is to re-throw with the proper exception, such that the calling logic
                // can route.
                throw new InvalidJsonException(iae);
            }
        }
    });

    return contextHolder.get();
}
 
Example #3
Source File: JacksonJsonEngine.java    From client-encryption-java with MIT License 5 votes vote down vote up
@Override
public Object parse(String string) {
    try {
        return jsonProvider.parse(string);
    } catch (InvalidJsonException e) {
        // Jackson refuses to parse primitive types
        return asPrimitiveValue(string);
    }
}
 
Example #4
Source File: SqlJsonFunctionsTest.java    From Quicksql with MIT License 5 votes vote down vote up
@Test public void testDejsonize() {
  assertDejsonize("{}",
      is(Collections.emptyMap()));
  assertDejsonize("[]",
      is(Collections.emptyList()));

  // expect exception thrown
  final String message = "com.fasterxml.jackson.core.JsonParseException: "
      + "Unexpected close marker '}': expected ']' (for Array starting at "
      + "[Source: (String)\"[}\"; line: 1, column: 1])\n at [Source: "
      + "(String)\"[}\"; line: 1, column: 3]";
  assertDejsonizeFailed("[}",
      errorMatches(new InvalidJsonException(message)));
}
 
Example #5
Source File: ScriptTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testAssigningRawTextWhichOtherwiseConfusesKarate() {
    ScenarioContext ctx = getContext();
    try {
        Script.assign("foo", "{ not json }", ctx);
        fail("we expected this to fail");
    } catch (InvalidJsonException e) {
        logger.debug("expected {}", e.getMessage());
    }
    Script.assign(AssignType.TEXT, "foo", "{ not json }", ctx, true);
    assertTrue(Script.matchNamed(MatchType.EQUALS, "foo", null, "'{ not json }'", ctx).pass);
}
 
Example #6
Source File: JsonPathSelector.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
@Override
public Object parse(String json) throws InvalidJsonException {
  try {
    return mapper.readValue(json, Object.class);
  } catch (IOException e) {
    throw new InvalidJsonException(e.getMessage(), e);
  }
}
 
Example #7
Source File: JsonPathSelector.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
@Override
public Object parse(InputStream jsonStream, String charset) throws InvalidJsonException {
  try {
    return mapper.readValue(new InputStreamReader(jsonStream, charset), Object.class);
  } catch (IOException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #8
Source File: SqlJsonFunctionsTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testDejsonize() {
  assertDejsonize("{}",
      is(Collections.emptyMap()));
  assertDejsonize("[]",
      is(Collections.emptyList()));

  // expect exception thrown
  final String message = "com.fasterxml.jackson.core.JsonParseException: "
      + "Unexpected close marker '}': expected ']' (for Array starting at "
      + "[Source: (String)\"[}\"; line: 1, column: 1])\n at [Source: "
      + "(String)\"[}\"; line: 1, column: 3]";
  assertDejsonizeFailed("[}",
      errorMatches(new InvalidJsonException(message)));
}
 
Example #9
Source File: JsonPathBaseEvaluator.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected DocumentContext getDocumentContext(EvaluationContext context) {
    final String subjectValue = subject.evaluate(context).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);
    }
    return documentContext;
}
 
Example #10
Source File: MarcFieldExtractor.java    From metadata-qa-marc with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void measure(JsonPathCache cache)
      throws InvalidJsonException {
  valid = true;
  resultMap = new FieldCounter<>();
  duplumKeyMap = null;
  recordId = null;
  leader = null;
  x007 = null;
  x008 = null;
  titleWords = null;
  authorWords = null;
  duplumKeyType = null;
  dateOfPublication = null;
  isbn = null;
  publisherOrDistributorNumber = null;
  abbreviatedNameOfPublisher = null;
  numberOfPart = null;
  nameOfPart = null;
  extent = null;
  musicalPresentationStatement = null;
  volumeDesignation = null;
  relatedParts = null;
  systemControlNumbers = null;
  oclcMap = null;

  recordId = ((List<XmlFieldInstance>) cache.get(getIdPath())).get(0).getValue();
  cache.setRecordId(recordId);
  resultMap.put(FIELD_NAME, Arrays.asList(recordId));
  if (schema != null) {
    String path;
    for (String fieldName : schema.getExtractableFields().keySet()) {
      if (!fieldName.equals(FIELD_NAME)) {
        path = schema.getExtractableFields().get(fieldName);
        List<XmlFieldInstance> instances = (List<XmlFieldInstance>) cache.get(path);
        List<String> values = null;
        if (!isNull(instances)) {
          values = new ArrayList<>();
          for (XmlFieldInstance instance : instances) {
            values.add(instance.getValue());
          }
          if (fieldName.equals("leader")) {
            leader = new Leader(values.get(0));
          }
        }
        resultMap.put(fieldName, values);
      }
    }
  }
  processLeader();
  process007();
  process008();
  processType();
  processTitleWords();
  processAuthorWords();
  processDateOfPublication();
  processIsbn();
  processPublisherOrDistributorNumber();
  processAbbreviatedNameOfPublisher();
  processNumberOfPart();
  processNameOfPart();
  processExtent();
  processMusicalPresentationStatement();
  processVolumeDesignation();
  processRelatedParts();
  processSystemControlNumbers();
  processOclcFields();
  createDuplumKeyMap();
}
 
Example #11
Source File: MarcJsonCalculatorFacade.java    From metadata-qa-marc with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String measure(String jsonRecord) throws InvalidJsonException {
  return this.<EdmFieldInstance>measureWithGenerics(jsonRecord);
}