Java Code Examples for com.jayway.jsonpath.DocumentContext#jsonString()

The following examples show how to use com.jayway.jsonpath.DocumentContext#jsonString() . 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: FieldLevelEncryption.java    From client-encryption-java with MIT License 6 votes vote down vote up
/**
 * Encrypt parts of a JSON payload using the given parameters and configuration.
 * @param payload A JSON string
 * @param config A {@link com.mastercard.developer.encryption.FieldLevelEncryptionConfig} instance
 * @param params A {@link FieldLevelEncryptionParams} instance
 * @return The updated payload
 * @throws EncryptionException
 */
public static String encryptPayload(String payload, FieldLevelEncryptionConfig config, FieldLevelEncryptionParams params) throws EncryptionException {
    try {
        // Parse the given payload
        DocumentContext payloadContext = JsonPath.parse(payload, jsonPathConfig);

        // Perform encryption (if needed)
        for (Entry<String, String> entry : config.encryptionPaths.entrySet()) {
            String jsonPathIn = entry.getKey();
            String jsonPathOut = entry.getValue();
            encryptPayloadPath(payloadContext, jsonPathIn, jsonPathOut, config, params);
        }

        // Return the updated payload
        return payloadContext.jsonString();
    } catch (GeneralSecurityException e) {
        throw new EncryptionException("Payload encryption failed!", e);
    }
}
 
Example 2
Source File: JSONIO.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
public void writeJSON( File target, DocumentContext contents ) throws ManipulationException
{
    try
    {
        PrettyPrinter dpp = new MyPrettyPrinter( getCharset() );
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = contents.jsonString();
        String pretty = mapper.writer( dpp ).writeValueAsString( mapper.readValue( jsonString, Object.class ) );
        Charset cs = getCharset();
        FileOutputStream fileOutputStream = new FileOutputStream( target );
        try (OutputStreamWriter p = new OutputStreamWriter( fileOutputStream, cs ) )
        {
            p.write( pretty );
            p.append( getEOL() );
        }
    }
    catch ( IOException e )
    {
        logger.error( "Unable to write JSON string:  ", e );
        throw new ManipulationException( "Unable to write JSON string", e );
    }
}
 
Example 3
Source File: JsonFunctions.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static String jsonRemove(JsonValueContext input, String... pathSpecs) {
  try {
    DocumentContext ctx = JsonPath.parse(input.obj,
        Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .jsonProvider(JSON_PATH_JSON_PROVIDER)
            .mappingProvider(JSON_PATH_MAPPING_PROVIDER)
            .build());
    for (String pathSpec : pathSpecs) {
      if ((pathSpec != null) && (ctx.read(pathSpec) != null)) {
        ctx.delete(pathSpec);
      }
    }
    return ctx.jsonString();
  } catch (Exception ex) {
    throw RESOURCE.invalidInputForJsonRemove(
        input.toString(), Arrays.toString(pathSpecs)).ex();
  }
}
 
Example 4
Source File: ResponseTemplateProcessor.java    From restdocs-wiremock with Apache License 2.0 6 votes vote down vote up
String replaceTemplateFields() {
    if (templateDescriptors.isEmpty()) {
        return responseBody;
    }

    DocumentContext documentContext = JsonPath.parse(responseBody);

    for (ResponseFieldTemplateDescriptor descriptor: templateDescriptors) {
        String expression = null;
        if (uriTemplate != null && !uriTemplate.getVariableNames().isEmpty()) {
            expression = preProcessUriTemplateVariableNameExpression(descriptor);
        } else if (descriptor.getUriTemplateVariableName() != null) {
            throw new IllegalArgumentException("Descriptor for field '" + descriptor.getPath() + "' specifies a 'replacedWithUriTemplateVariableValue' but no URI Template could be found in. " +
                    "Make sure to construct your request with the methods in org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders that use URI templates");
        }
        if (expression == null) {
            if (descriptor.getWireMockTemplateExpression() == null) {
                throw new IllegalArgumentException("Descriptor for field '" + descriptor.getPath() + "' contains no replacedWithWireMockTemplateExpression");
            }
            expression = "{{" + descriptor.getWireMockTemplateExpression() + "}}";
        }
        documentContext.set(descriptor.getPath(), expression);
    }
    return documentContext.jsonString();
}
 
Example 5
Source File: JsonUtilsTest.java    From karate with MIT License 6 votes vote down vote up
@Test
public void testEmptyJsonArray() {
    DocumentContext doc = JsonUtils.emptyJsonArray(0);
    String json = doc.jsonString();
    assertEquals("[]", json);
    doc = JsonUtils.emptyJsonArray(1);
    json = doc.jsonString();
    assertEquals("[{}]", json);
    doc = JsonUtils.emptyJsonArray(2);
    json = doc.jsonString();
    assertEquals("[{},{}]", json);
}
 
Example 6
Source File: JsonFunctions.java    From Quicksql with MIT License 6 votes vote down vote up
public static String jsonRemove(JsonValueContext input, String... pathSpecs) {
  try {
    DocumentContext ctx = JsonPath.parse(input.obj,
        Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .jsonProvider(JSON_PATH_JSON_PROVIDER)
            .mappingProvider(JSON_PATH_MAPPING_PROVIDER)
            .build());
    for (String pathSpec : pathSpecs) {
      if ((pathSpec != null) && (ctx.read(pathSpec) != null)) {
        ctx.delete(pathSpec);
      }
    }
    return ctx.jsonString();
  } catch (Exception ex) {
    throw RESOURCE.invalidInputForJsonRemove(
        input.toString(), Arrays.toString(pathSpecs)).ex();
  }
}
 
Example 7
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 6 votes vote down vote up
/**
 * Decrypt parts of a JSON payload using the given parameters and configuration.
 * @param payload A JSON string
 * @param config A {@link com.mastercard.developer.encryption.FieldLevelEncryptionConfig} instance
 * @param params A {@link FieldLevelEncryptionParams} instance
 * @return The updated payload
 * @throws EncryptionException
 */
public static String decryptPayload(String payload, FieldLevelEncryptionConfig config, FieldLevelEncryptionParams params) throws EncryptionException {
    try {
        // Parse the given payload
        DocumentContext payloadContext = JsonPath.parse(payload, jsonPathConfig);

        // Perform decryption (if needed)
        for (Entry<String, String> entry : config.decryptionPaths.entrySet()) {
            String jsonPathIn = entry.getKey();
            String jsonPathOut = entry.getValue();
            decryptPayloadPath(payloadContext, jsonPathIn, jsonPathOut, config, params);
        }

        // Return the updated payload
        return payloadContext.jsonString();
    } catch (GeneralSecurityException e) {
        throw new EncryptionException("Payload decryption failed!", e);
    }
}
 
Example 8
Source File: ScriptValue.java    From karate with MIT License 5 votes vote down vote up
public String getAsString() {
    switch (type) {
        case NULL:
            return null;
        case JSON:
            DocumentContext doc = getValue(DocumentContext.class);
            return doc.jsonString();
        case XML:
            Node node = getValue(Node.class);
            if (node.getTextContent() != null) { // for attributes, text() etc
                return node.getTextContent();
            } else {
                return XmlUtils.toString(node);
            }
        case LIST:
            List list = getAsList();
            DocumentContext listDoc = JsonPath.parse(list);
            return listDoc.jsonString();
        case MAP:
            DocumentContext mapDoc = JsonPath.parse(getAsMap());
            return mapDoc.jsonString();
        case JS_FUNCTION:
            return value.toString().replace("\n", " ");
        case BYTE_ARRAY:
            return FileUtils.toString(getValue(byte[].class));
        case INPUT_STREAM:
            return FileUtils.toString(getValue(InputStream.class));
        default:
            return value.toString();
    }
}
 
Example 9
Source File: JsonUtilsTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testEmptyJsonObject() {
    DocumentContext doc = JsonUtils.emptyJsonObject();
    String json = doc.jsonString();
    assertEquals("{}", json);
}
 
Example 10
Source File: PSQLXyzConnectorIT.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteFeatures() 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);

  // =========== DELETE ==========
  final DocumentContext modifyFeaturesEventDoc = getEventFromResource("/events/InsertFeaturesEvent.json");
  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);
  logger.info("Modify features tested successfully");

}
 
Example 11
Source File: ScriptTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testEvalEmbeddedExpressionsWithJsonPath() {
    ScenarioContext ctx = getContext();
    String ticket = "{ ticket: 'my-ticket', userId: '12345' }";
    ctx.vars.put("ticket", JsonUtils.toJsonDoc(ticket));
    String json = "{ foo: '#(ticket.userId)' }";
    DocumentContext doc = JsonUtils.toJsonDoc(json);
    Script.evalJsonEmbeddedExpressions(doc, ctx);
    String result = doc.jsonString();
    logger.debug("result: {}", result);
    assertEquals("{\"foo\":\"12345\"}", result);
}
 
Example 12
Source File: Module.java    From synthea with Apache License 2.0 5 votes vote down vote up
private static String applyOverrides(String jsonString, Properties overrides,
        String moduleFileName) {
  DocumentContext ctx = JsonPath.using(JSON_PATH_CONFIG).parse(jsonString);
  overrides.forEach((key, value) -> {
    // use :: for the separator because filenames cannot contain :
    String[] parts = ((String)key).split("::");
    String module = parts[0];
    if (module.equals(moduleFileName)) {
      String jsonPath = parts[1];
      Double numberValue = Double.parseDouble((String)value);
      ctx.set(jsonPath, numberValue);
    }
  });
  return ctx.jsonString();
}
 
Example 13
Source File: PSQLXyzConnectorIT.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private void testDeleteFeaturesByTag(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);
    logger.info("Preparation: Insert features");

    // =========== COUNT ==========
    String countResponse = invokeLambdaFromFile("/events/CountFeaturesEvent.json");
    Integer originalCount = JsonPath.read(countResponse, "$.count");
    logger.info("Preparation: feature count = {}", originalCount);

    // =========== DELETE SOME TAGGED FEATURES ==========
    logger.info("Delete tagged features");
    final DocumentContext deleteByTagEventDoc = getEventFromResource("/events/DeleteFeaturesByTagEvent.json");
    deleteByTagEventDoc.put("$", "params", Collections.singletonMap("includeOldStates", includeOldStates));
    String[][] tags = {{"yellow"}};
    deleteByTagEventDoc.put("$", "tags", tags);
    String deleteByTagEvent = deleteByTagEventDoc.jsonString();
    String deleteByTagResponse = invokeLambda(deleteByTagEvent);
    assertNoErrorInResponse(deleteByTagResponse);
    final JsonPath jsonPathFeatures = JsonPath.compile("$.features");
    @SuppressWarnings("rawtypes") List features = jsonPathFeatures.read(deleteByTagResponse, jsonPathConf);
    if (includeOldStates) {
      assertNotNull("'features' element in DeleteByTagResponse is missing", features);
      assertTrue("'features' element in DeleteByTagResponse is empty", features.size() > 0);
    } else if (features != null) {
      assertEquals("unexpected features in DeleteByTagResponse", 0, features.size());
    }

    countResponse = invokeLambdaFromFile("/events/CountFeaturesEvent.json");
    Integer count = JsonPath.read(countResponse, "$.count");
    assertTrue(originalCount > count);
    logger.info("Delete tagged features tested successfully");

    // =========== DELETE ALL FEATURES ==========
    deleteByTagEventDoc.put("$", "tags", null);
    String deleteAllEvent = deleteByTagEventDoc.jsonString();
    String deleteAllResponse = invokeLambda(deleteAllEvent);
    assertNoErrorInResponse(deleteAllResponse);
    features = jsonPathFeatures.read(deleteAllResponse, jsonPathConf);
    if (features != null) {
      assertEquals("unexpected features in DeleteByTagResponse", 0, features.size());
    }

    // TODO use deleted.length() when it's available
//    if (includeOldStates) {
//      final JsonPath jsonPathDeletedCount = JsonPath.compile("$.deletedCount");
//      Integer deletedCount = jsonPathDeletedCount.read(deleteAllResponse, jsonPathConf);
//      assertNotNull("'deletedCount' element in DeleteByTagResponse is missing", deletedCount);
//    }

    countResponse = invokeLambdaFromFile("/events/CountFeaturesEvent.json");
    count = JsonPath.read(countResponse, "$.count");
    assertEquals(0, count.intValue());
    logger.info("Delete all features tested successfully");
  }
 
Example 14
Source File: CommonG.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a subelement in a JsonPath
 *
 * @param jsonString String of the json
 * @param expr       regex to be removed
 */

public String removeJSONPathElement(String jsonString, String expr) {

    Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build();
    DocumentContext context = JsonPath.using(conf).parse(jsonString);
    context.delete(expr);
    return context.jsonString();
}
 
Example 15
Source File: OpenAPIV2Generator.java    From spring-openapi with MIT License 5 votes vote down vote up
public String generateJson(OpenApiV2GeneratorConfig config) throws JsonProcessingException {
	Swagger openAPI = generate(config);
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	DocumentContext doc = JsonPath.parse(objectMapper.writeValueAsString(openAPI));
	doc.delete("$..responseSchema");
	doc.delete("$..originalRef");
	return doc.jsonString();
}
 
Example 16
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 17
Source File: JsonUtils.java    From karate with MIT License 4 votes vote down vote up
public static String toStrictJsonString(String raw) {
    DocumentContext dc = toJsonDoc(raw);
    return dc.jsonString();
}