Java Code Examples for com.jayway.jsonpath.DocumentContext#delete()
The following examples show how to use
com.jayway.jsonpath.DocumentContext#delete() .
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 |
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 2
Source File: JsonFunctions.java From Quicksql with MIT License | 6 votes |
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 3
Source File: JsonFunctions.java From calcite with Apache License 2.0 | 6 votes |
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: OpenAPIV2Generator.java From spring-openapi with MIT License | 5 votes |
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 5
Source File: FieldLevelEncryption.java From client-encryption-java with MIT License | 5 votes |
private static Object readAndDeleteJsonKey(DocumentContext context, String objectPath, Object object, String key) { if (null == key) { // Do nothing return null; } JsonProvider jsonProvider = jsonPathConfig.jsonProvider(); Object value = jsonProvider.getMapValue(object, key); context.delete(objectPath + "." + key); return value; }
Example 6
Source File: PSQLXyzConnectorIT.java From xyz-hub with Apache License 2.0 | 5 votes |
@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: CommonG.java From bdt with Apache License 2.0 | 5 votes |
/** * 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 8
Source File: JSONIOTest.java From pom-manipulation-ext with Apache License 2.0 | 5 votes |
@Test public void modifyFile () throws ManipulationException, IOException { String deletePath = "$..resolved"; DocumentContext doc = jsonIO.parseJSON( npmFile ); doc.delete(deletePath); File target = tf.newFile(); jsonIO.writeJSON( target, doc ); assertFalse ( FileUtils.contentEquals( npmFile, target ) ); }
Example 9
Source File: JSONIOTest.java From pom-manipulation-ext with Apache License 2.0 | 5 votes |
@Test public void modifyPartialFile () throws ManipulationException, IOException { String deletePath = "$.dependencies.agent-base..resolved"; DocumentContext doc = jsonIO.parseJSON( npmFile ); doc.delete(deletePath); File target = tf.newFile(); jsonIO.writeJSON( target, doc ); assertFalse ( doc.jsonString().contains( "https://registry.npmjs.org/agent-base/-/agent-base-2.0.1.tgz" ) ); assertTrue ( doc.jsonString().contains( "resolved" ) ); }
Example 10
Source File: FieldLevelEncryption.java From client-encryption-java with MIT License | 4 votes |
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 11
Source File: FieldLevelEncryption.java From client-encryption-java with MIT License | 4 votes |
private static void decryptPayloadPath(DocumentContext payloadContext, String jsonPathIn, String jsonPathOut, FieldLevelEncryptionConfig config, FieldLevelEncryptionParams params) throws GeneralSecurityException, EncryptionException { JsonProvider jsonProvider = jsonPathConfig.jsonProvider(); Object inJsonObject = readJsonObject(payloadContext, jsonPathIn); if (inJsonObject == null) { // Nothing to decrypt return; } // Read and remove encrypted data and encryption fields at the given JSON path Object encryptedValueJsonElement = readAndDeleteJsonKey(payloadContext, jsonPathIn, inJsonObject, config.encryptedValueFieldName); if (jsonEngine.isNullOrEmptyJson(encryptedValueJsonElement)) { // Nothing to decrypt return; } if (!config.useHttpPayloads() && params == null) { throw new IllegalStateException("Encryption params have to be set when not stored in HTTP payloads!"); } if (params == null) { // Read encryption params from the payload Object oaepDigestAlgorithmJsonElement = readAndDeleteJsonKey(payloadContext, jsonPathIn, inJsonObject, config.oaepPaddingDigestAlgorithmFieldName); String oaepDigestAlgorithm = jsonEngine.isNullOrEmptyJson(oaepDigestAlgorithmJsonElement) ? config.oaepPaddingDigestAlgorithm : jsonEngine.toJsonString(oaepDigestAlgorithmJsonElement); Object encryptedKeyJsonElement = readAndDeleteJsonKey(payloadContext, jsonPathIn, inJsonObject, config.encryptedKeyFieldName); Object ivJsonElement = readAndDeleteJsonKey(payloadContext, jsonPathIn, inJsonObject, config.ivFieldName); readAndDeleteJsonKey(payloadContext, jsonPathIn, inJsonObject, config.encryptionCertificateFingerprintFieldName); readAndDeleteJsonKey(payloadContext, jsonPathIn, inJsonObject, config.encryptionKeyFingerprintFieldName); params = new FieldLevelEncryptionParams(jsonEngine.toJsonString(ivJsonElement), jsonEngine.toJsonString(encryptedKeyJsonElement), oaepDigestAlgorithm, config); } // Decrypt data byte[] encryptedValueBytes = decodeValue(jsonEngine.toJsonString(encryptedValueJsonElement), config.fieldValueEncoding); byte[] decryptedValueBytes = decryptBytes(params.getSecretKey(), params.getIvSpec(), encryptedValueBytes); // Add decrypted data at the given JSON path String decryptedValue = new String(decryptedValueBytes, StandardCharsets.UTF_8); decryptedValue = sanitizeJson(decryptedValue); checkOrCreateOutObject(payloadContext, jsonPathOut); addDecryptedDataToPayload(payloadContext, decryptedValue, jsonPathOut); // Remove the input if now empty Object inJsonElement = readJsonElement(payloadContext, jsonPathIn); if (0 == jsonProvider.length(inJsonElement) && !"$".equals(jsonPathIn)) { payloadContext.delete(jsonPathIn); } }
Example 12
Source File: PSQLXyzConnectorIT.java From xyz-hub with Apache License 2.0 | 4 votes |
@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 13
Source File: JSONManipulator.java From pom-manipulation-ext with Apache License 2.0 | 4 votes |
void internalApplyChanges( Project project, JSONState.JSONOperation operation ) throws ManipulationException { File target = new File( project.getPom().getParentFile(), operation.getFile() ); logger.info( "Attempting to start JSON update to file {} with xpath {} and replacement '{}' ", target, operation.getXPath(), operation.getUpdate() ); DocumentContext dc = null; try { if ( !target.exists() ) { logger.error( "Unable to locate JSON file {} ", target ); throw new ManipulationException( "Unable to locate JSON file {}", target ); } dc = jsonIO.parseJSON( target ); List<?> o = dc.read( operation.getXPath() ); if ( o.size() == 0 ) { if ( project.isIncrementalPME() ) { logger.warn ("Did not locate JSON using XPath " + operation.getXPath() ); return; } else { logger.error( "XPath {} did not find any expressions within {} ", operation.getXPath(), operation.getFile() ); throw new ManipulationException( "XPath did not resolve to a valid value" ); } } if ( isEmpty( operation.getUpdate() ) ) { // Delete logger.info( "Deleting {} on {}", operation.getXPath(), dc ); dc.delete( operation.getXPath() ); } else { // Update logger.info( "Updating {} on {}", operation.getXPath(), dc ); dc.set( operation.getXPath(), operation.getUpdate() ); } jsonIO.writeJSON( target, dc ); } catch ( JsonPathException e ) { logger.error( "Caught JSON exception processing file {}, document context {} ", target, dc, e ); throw new ManipulationException( "Caught JsonPath", e ); } }