public static String maskJson(DocumentContext ctx, String key) { Map<String, Object> jsonConfig = (Map<String, Object>) config.get(MASK_TYPE_JSON); if (jsonConfig != null) { Map<String, Object> patternMap = (Map<String, Object>) jsonConfig.get(key); if (patternMap != null) { JsonNode configNode = Config.getInstance().getMapper().valueToTree(patternMap); Iterator<Map.Entry<String, JsonNode>> iterator = configNode.fields(); while (iterator.hasNext()) { Map.Entry<String, JsonNode> entry = iterator.next(); applyMask(entry, ctx); } return ctx.jsonString(); } else { logger.warn("mask.json doesn't contain the key {} ", Encode.forJava(key)); } } return ctx.jsonString(); }
@Test public void json_can_be_fetched_as_string() { String expected = "{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"display-price\":8.95}"; String jsonString1 = using(JSON_SMART_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); String jsonString2 = using(JACKSON_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); String jsonString3 = using(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); String jsonString4 = using(GSON_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); Assertions.assertThat(jsonString1).isEqualTo(expected); Assertions.assertThat(jsonString2).isEqualTo(expected); Assertions.assertThat(jsonString3).isEqualTo(expected); Assertions.assertThat(jsonString4).isEqualTo(expected); }
private static void maskList(DocumentContext ctx, String jsonPath, String expression) { ctx.configuration().addOptions(Option.AS_PATH_LIST); Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build(); DocumentContext context = JsonPath.using(conf).parse(ctx.jsonString()); List<String> pathList = context.read(jsonPath); /** * when reach here, ctx.read(jsonPath) should only give us a list of strings so that we can replace with MASK_REPLACEMENT_CHAR * list of values can belongs to a same path or different paths, we should treat differently. * two situations: * an array contains multiple String values like: "list": ["ab", "cd", "ef] * or single value belongs to different paths. */ if(pathList != null && pathList.size() == 1) { String path = pathList.get(0); List values = ctx.read(path); JSONArray maskedValue = new JSONArray(); //mask each value in the list of the same path values.forEach(o -> maskedValue.add(replaceWithMask(o.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression))); ctx.set(path, maskedValue); } else { for (String path : Optional.ofNullable(pathList).orElse(Collections.emptyList())) { Object value = ctx.read(path); ctx.set(path, replaceWithMask(value.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression)); } } }
@Test public void mapPropertyWithPOJO() { String someJson = "" + "{\n" + " \"a\": \"a\",\n" + " \"b\": \"b\"\n" + "}"; ObjectMapper om = new ObjectMapper(); om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); Configuration c = Configuration .builder() .mappingProvider(new JacksonMappingProvider()) .jsonProvider(new JacksonJsonNodeJsonProvider(om)) .build(); DocumentContext context = JsonPath.using(c).parse(someJson); String someJsonStr = context.jsonString(); DocumentContext altered = context.map("$['a', 'b', 'c']", new MapFunction() { @Override public Object map(Object currentValue, Configuration configuration) { return currentValue; } }); assertThat(altered.jsonString()).isEqualTo(someJsonStr); }
private static final Object extractValueFromResponse(Map response, String jsonPath) { Object jsonResponse = response.get("value"); assertNotNull(jsonResponse); String json = JsonPath.parse(jsonResponse).jsonString(); Object value = JsonPath.parse(json, JSON_PATH_CONFIG).read(jsonPath); return value; }
@Override public String toString() { return doc.jsonString(); }
public static String toStrictJsonString(String raw) { DocumentContext dc = toJsonDoc(raw); return dc.jsonString(); }
public static String maskJson(DocumentContext ctx, String key) { Map<String, Object> jsonConfig = (Map<String, Object>) config.get(MASK_TYPE_JSON); if (jsonConfig != null) { Map<String, Object> patternMap = (Map<String, Object>) jsonConfig.get(key); if (patternMap != null) { JsonNode configNode = Config.getInstance().getMapper().valueToTree(patternMap); Iterator<Map.Entry<String, JsonNode>> iterator = configNode.fields(); while (iterator.hasNext()) { Map.Entry<String, JsonNode> entry = iterator.next(); applyMask(entry, ctx); } return ctx.jsonString(); } else { logger.warn("mask.json doesn't contain the key {} ", Encode.forJava(key)); } } return ctx.jsonString(); }
public void setGenerateReports(boolean generateReports) { jsonData = JsonPath.parse(jsonData).set("$.generateReports", generateReports).jsonString(); }
public void setResultsOutputIsCSVFormat(boolean isCSVFormat) { jsonData = JsonPath.parse(jsonData).set("$.resultsOutputIsCSVFormat", isCSVFormat).jsonString(); }
public void setResultsFileLocations(List<String> resultFileLocations) { jsonData = JsonPath.parse(jsonData).set("$.resultFilesLocations", resultFileLocations).jsonString(); }
public Object toBean(Object o, String className) { ScriptValue sv = new ScriptValue(o); DocumentContext doc = Script.toJsonDoc(sv, context); return JsonUtils.fromJson(doc.jsonString(), className); }
private JSONArray check(String jsonPathString) { if (jsonAsserterConfiguration.ignoreJsonPathException) { logOverridingWarning(); return null; } JSONArray array = jsonPathToArray(jsonPathString); if (array.isEmpty() || containsEmptyElementsOnly(array)) { throw new IllegalStateException("Parsed JSON [" + parsedJson.jsonString() + "] doesn't match the JSON path [" + jsonPathString + "]"); } return array; }
@Override public JsonVerifiable isEmpty() throws IllegalStateException { if (jsonAsserterConfiguration.ignoreJsonPathException) { logOverridingWarning(); return this; } String jsonPathString = createJsonPathString(); Object o = parsedJson.read(jsonPathString); if (!isObjectEmpty(o)) { throw new IllegalStateException("Parsed JSON [" + parsedJson.jsonString() + "] with the JSON path [" + jsonPathString + "] is not empty!"); } return this; }
@Override public ValidationResult validate(ScriptValue value) { switch(value.getType()) { case JSON: DocumentContext doc = value.getValue(DocumentContext.class); if (!doc.jsonString().startsWith("[")) { return ValidationResult.fail("not an array or list"); } else { return ValidationResult.PASS; } case JS_ARRAY: case LIST: return ValidationResult.PASS; default: return ValidationResult.fail("not an array or list"); } }
@Override public JsonVerifiable hasSize(int size) { if (jsonAsserterConfiguration.ignoreJsonPathException) { logOverridingWarning(); return this; } JSONArray array = checkBufferedJsonPathString(); if (array == null || array.size() != size) { throw new IllegalStateException("Parsed JSON <" + parsedJson.jsonString() + "> doesn't have the " + "size <" + size + "> for JSON path <" + createJsonPathString()+ ">. The size is <" + (array == null ? null : array.size()) + ">"); } return this; }
@Override public ValidationResult validate(ScriptValue value) { switch(value.getType()) { case JSON: DocumentContext doc = value.getValue(DocumentContext.class); if (!doc.jsonString().startsWith("{")) { return ValidationResult.fail("not a json object"); } else { return ValidationResult.PASS; } case JS_OBJECT: case MAP: return ValidationResult.PASS; default: return ValidationResult.fail("not a json object"); } }
public String updateJsonPathWithValue(String json, String jsonPath, Object value) { if(null != getJsonPath(json, jsonPath)) { return parseJson(json).set(jsonPath, value).jsonString(); } else { throw new PathNotFoundException("No result for: " + jsonPath + " IN: " + json); } }
public static String forCards(String body) { DocumentContext context = JsonPath.using(configuration).parse(body); context.set("$.cards[?(@.id =~ /" + UUID_PATTERN + "/)].id", DUMMY_UUID); context.set("$.cards[?(@.creation_date =~ /" + DATE_PATTERN + "/)].creation_date", DUMMY_DATE_TIME); context.set("$.cards[?(@.expiration_date =~ /" + DATE_PATTERN + "/)].expiration_date", DUMMY_DATE_TIME); context.set("$.cards[*].actions[?(@.id =~ /" + UUID_PATTERN + "/)].id", DUMMY_UUID); return context.jsonString(); } }
private void assertTest123CollectionCreated() throws Exception { // check it's really there DocumentContext json = getAsJSONPath("/rest/oseo/collections/TEST123", 200); assertEquals("TEST123", json.read("$.id")); assertEquals("Feature", json.read("$.type")); assertEquals("TEST123", json.read("$.properties.name")); assertEquals("S2MS1C", json.read("$.properties['eo:productType']")); assertEquals("A", json.read("$.properties['eo:platformSerialIdentifier']")); assertEquals("MSI", json.read("$.properties['eo:instrument']")); assertEquals("2012-04-23T18:25:43.511+0000", json.read("$.properties['timeStart']")); SimpleFeature sf = new FeatureJSON().readFeature(json.jsonString()); ReferencedEnvelope bounds = ReferencedEnvelope.reference(sf.getBounds()); assertTrue(new Envelope(-180, 180, -90, 90).equals(bounds)); } }