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

The following examples show how to use com.jayway.jsonpath.DocumentContext#put() . 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: JsonSetter.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {
	
	if( getWhere().equals("") )
		return input; 
	
	DocumentContext document = JsonPath.parse(new String(input));
	
	try {
		document.read(getWhere());
	} catch( Exception e ) {
		
		if( !addIfNotPresent.isSelected() )
			throw new IllegalArgumentException("Key not found.");
		
		String insertPath = this.path.getText();
		if( insertPath.equals("Insert-Path") || insertPath.equals("") )
			insertPath = "$";
			
		document = document.put(insertPath, getWhere(), getWhat());
		return document.jsonString().getBytes();
	}
	
	document.set(getWhere(), getWhat());
	return document.jsonString().getBytes();
}
 
Example 2
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 6 votes vote down vote up
private static void addDecryptedDataToPayload(DocumentContext payloadContext, String decryptedValue, String jsonPathOut) {
    JsonProvider jsonProvider = jsonPathConfig.jsonProvider();
    Object decryptedValueJsonElement = jsonEngine.parse(decryptedValue);

    if (!jsonEngine.isJsonObject(decryptedValueJsonElement)) {
        // Array or primitive: overwrite
        payloadContext.set(jsonPathOut, decryptedValueJsonElement);
        return;
    }

    // Object: merge
    int length = jsonProvider.length(decryptedValueJsonElement);
    Collection<String> propertyKeys = (0 == length) ? Collections.<String>emptyList() : jsonProvider.getPropertyKeys(decryptedValueJsonElement);
    for (String key : propertyKeys) {
        payloadContext.delete(jsonPathOut + "." + key);
        payloadContext.put(jsonPathOut, key, jsonProvider.getMapValue(decryptedValueJsonElement, key));
    }
}
 
Example 3
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 6 votes vote down vote up
private static void checkOrCreateOutObject(DocumentContext context, String jsonPathOutString) {
    Object outJsonObject = readJsonObject(context, jsonPathOutString);
    if (null != outJsonObject) {
        // Object already exists
        return;
    }

    // Path does not exist: if parent exists then we create a new object under the parent
    String parentJsonPath = JsonEngine.getParentJsonPath(jsonPathOutString);
    Object parentJsonObject = readJsonObject(context, parentJsonPath);
    if (parentJsonObject == null) {
        throw new IllegalArgumentException(String.format("Parent path not found in payload: '%s'!", parentJsonPath));
    }
    outJsonObject = jsonPathConfig.jsonProvider().createMap();
    String elementKey = JsonEngine.getJsonElementKey(jsonPathOutString);
    context.put(parentJsonPath, elementKey, outJsonObject);
}
 
Example 4
Source File: JsonPathIntegrationCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Integration apply(Integration integration) {
    if (ObjectHelper.isEmpty(expression)) {
        return integration;
    }

    try {
        final Configuration configuration = Configuration.builder()
                .jsonProvider(new JacksonJsonProvider(JsonUtils.copyObjectMapperConfiguration()))
                .mappingProvider(new JacksonMappingProvider(JsonUtils.copyObjectMapperConfiguration()))
                .build();

        DocumentContext json = JsonPath.using(configuration).parse(JsonUtils.writer().forType(Integration.class).writeValueAsString(integration));

        if (ObjectHelper.isEmpty(key)) {
            json.set(expression, value);
        } else {
            json.put(expression, key, value);
        }

        return JsonUtils.reader().forType(Integration.class).readValue(json.jsonString());
    } catch (IOException e) {
        throw new IllegalStateException("Failed to evaluate json path expression on integration object", e);
    }
}
 
Example 5
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 6
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 7
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 4 votes vote down vote up
private static void encryptPayloadPath(DocumentContext payloadContext, String jsonPathIn, String jsonPathOut,
                                       FieldLevelEncryptionConfig config, FieldLevelEncryptionParams params) throws GeneralSecurityException, EncryptionException {

    Object inJsonElement = readJsonElement(payloadContext, jsonPathIn);
    if (inJsonElement == null) {
        // Nothing to encrypt
        return;
    }

    if (params == null) {
        // Generate encryption params
        params = FieldLevelEncryptionParams.generate(config);
    }

    // Encrypt data at the given JSON path
    String inJsonString = sanitizeJson(jsonEngine.toJsonString(inJsonElement));
    byte[] inJsonBytes = null;
    try {
        inJsonBytes = inJsonString.getBytes(StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        // Should not happen
    }
    byte[] encryptedValueBytes = encryptBytes(params.getSecretKey(), params.getIvSpec(), inJsonBytes);
    String encryptedValue = encodeBytes(encryptedValueBytes, config.fieldValueEncoding);

    // Delete data in clear
    if (!"$".equals(jsonPathIn)) {
        payloadContext.delete(jsonPathIn);
    } else {
        // Delete keys one by one
        Collection<String> propertyKeys = new ArrayList<>(jsonEngine.getPropertyKeys(inJsonElement));
        for (String key : propertyKeys) {
            payloadContext.delete(jsonPathIn + "." + key);
        }
    }

    // Add encrypted data and encryption fields at the given JSON path
    checkOrCreateOutObject(payloadContext, jsonPathOut);
    payloadContext.put(jsonPathOut, config.encryptedValueFieldName, encryptedValue);
    if (!isNullOrEmpty(config.ivFieldName)) {
        payloadContext.put(jsonPathOut, config.ivFieldName, params.getIvValue());
    }
    if (!isNullOrEmpty(config.encryptedKeyFieldName)) {
        payloadContext.put(jsonPathOut, config.encryptedKeyFieldName, params.getEncryptedKeyValue());
    }
    if (!isNullOrEmpty(config.encryptionCertificateFingerprintFieldName)) {
        payloadContext.put(jsonPathOut, config.encryptionCertificateFingerprintFieldName, config.encryptionCertificateFingerprint);
    }
    if (!isNullOrEmpty(config.encryptionKeyFingerprintFieldName)) {
        payloadContext.put(jsonPathOut, config.encryptionKeyFingerprintFieldName, config.encryptionKeyFingerprint);
    }
    if (!isNullOrEmpty(config.oaepPaddingDigestAlgorithmFieldName)) {
        payloadContext.put(jsonPathOut, config.oaepPaddingDigestAlgorithmFieldName, params.getOaepPaddingDigestAlgorithmValue());
    }
}
 
Example 8
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");
}