com.jayway.jsonpath.JsonPath Java Examples
The following examples show how to use
com.jayway.jsonpath.JsonPath.
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: ZeroCodeAssertionsProcessorImplTest.java From zerocode with Apache License 2.0 | 8 votes |
@Test public void testJsonPathValue_isSingleField() { String scenarioStateJson = "{\n" + " \"type\": \"fuzzy\",\n" + " \"results\": [\n" + " {\n" + " \"id\": \"id-001\",\n" + " \"name\": \"Emma\"\n" + " },\n" + " {\n" + " \"id\": \"id-002\",\n" + " \"name\": \"Nikhi\"\n" + " }\n" + " ]\n" + "}"; Object jsonPathValue = JsonPath.read(scenarioStateJson, "$.type"); assertThat(jsonPathValue + "", is("fuzzy")); assertThat(jsonPreProcessor.isPathValueJson(jsonPathValue), is(false)); }
Example #2
Source File: IntegrationTest.java From kubernetes-integration-test with Apache License 2.0 | 6 votes |
@Test public void testSucc() throws Exception { log.info("Send testSucc"); jmsTemplate.convertAndSend("user.in", "{\"email\":\"[email protected]\"}"); TextMessage message = (TextMessage) jmsTemplate.receive("user.out"); String response = message.getText(); log.info("Response: {}",response); assertEquals("[email protected]", JsonPath.read(response, "$.email")); assertEquals("5551234567", JsonPath.read(response, "$.phone")); assertEquals("Test State", JsonPath.read(response, "$.address.state")); assertEquals("Test City", JsonPath.read(response, "$.address.city")); assertEquals("1 Test St", JsonPath.read(response, "$.address.address")); assertEquals("T001", JsonPath.read(response, "$.address.zip")); }
Example #3
Source File: Verify.java From dew with Apache License 2.0 | 6 votes |
/** * Verify resource descriptors. * * @param message the message * @param expectedText the expected text * @param actualText the actual text * @throws IOException the io exception * @throws ParseException the parse exception */ default void verifyResourceDescriptors(String message, String expectedText, String actualText) throws IOException, ParseException { JsonTextMessageValidator validator = new JsonTextMessageValidator(); validator.setStrict(false); TestContext context = new TestContext(); context.getValidationMatcherRegistry() .getValidationMatcherLibraries() .add(new ValidationMatcherConfig().getValidationMatcherLibrary()); validator.validateJson(message, (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(actualText)), (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(expectedText)), new JsonMessageValidationContext(), context, JsonPath.parse(actualText)); }
Example #4
Source File: SessionsTest.java From lannister with Apache License 2.0 | 6 votes |
@Test public void testLive() throws Exception { ConnectOptions options = new ConnectOptions(); options.clientId(TestUtil.newClientId()); MqttClient client = new MqttClient("mqtt://localhost:" + Settings.INSTANCE.mqttPort()); MqttConnectReturnCode ret = client.connectOptions(options).connect(); Assert.assertEquals(MqttConnectReturnCode.CONNECTION_ACCEPTED, ret); Assert.assertTrue(client.isConnected()); HttpClient httpClient = new HttpClient( "http://localhost:" + Settings.INSTANCE.httpPort() + "/api/sessions?filter=live"); HttpResponse res = httpClient.get(); Assert.assertEquals(HttpResponseStatus.OK, res.status()); Assert.assertEquals(new Integer(1), JsonPath.read(res.content().toString(CharsetUtil.UTF_8), "$.length()")); client.disconnect(true); Assert.assertFalse(client.isConnected()); }
Example #5
Source File: JsonSetter.java From cstc with GNU General Public License v3.0 | 6 votes |
@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 #6
Source File: JsonExtractor.java From cstc with GNU General Public License v3.0 | 6 votes |
@Override protected byte[] perform(byte[] input) throws Exception { if( fieldTxt.getText().equals("") ) return input; Object document = provider.parse(new String(input)); Object result = JsonPath.read(document, fieldTxt.getText()); if( result == null ) result = "null"; Class<? extends Object> resultClass = result.getClass(); if( resultClass == String.class ) { return ((String)result).getBytes(); } else if( resultClass == Integer.class || resultClass == Float.class || resultClass == Double.class ) { return String.valueOf(result).getBytes(); } else if( resultClass == Boolean.class ) { return String.valueOf(result).getBytes(); } throw new IllegalArgumentException("JSON data of unknown type."); }
Example #7
Source File: FUN_JSONPath.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public NodeValue exec(NodeValue json, NodeValue jsonpath) { if (json.getDatatypeURI() != null && !json.getDatatypeURI().equals(datatypeUri) && !json.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) { LOG.debug("The datatype of the first argument should be <" + datatypeUri + ">" + " or <http://www.w3.org/2001/XMLSchema#string>. Got " + json.getDatatypeURI()); } if (!jsonpath.isString()) { LOG.debug("The second argument should be a string. Got " + json); } try { Object value = JsonPath.parse(json.asNode().getLiteralLexicalForm()) .limit(1).read(jsonpath.getString()); return nodeForObject(value); } catch (Exception ex) { if(LOG.isDebugEnabled()) { Node compressed = LogUtils.compress(json.asNode()); LOG.debug("No evaluation of " + compressed + ", " + jsonpath); } throw new ExprEvalException("No evaluation of " + jsonpath); } }
Example #8
Source File: FieldLevelEncryption.java From client-encryption-java with MIT License | 6 votes |
/** * 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 #9
Source File: HttpUtils.java From cs-actions with Apache License 2.0 | 6 votes |
@NotNull public static Map<String, String> getFailureResults(@NotNull String inputName, @NotNull Integer statusCode, @NotNull String returnMessage, @NotNull String throwable) { Map<String, String> results = new HashMap(); results.put(RETURN_CODE, "-1"); results.put(STATUS_CODE, statusCode.toString()); if (statusCode.equals(401)) { results.put(RETURN_RESULT, inputName + " not found, or user unauthorized to perform action"); results.put(EXCEPTION, "status : " + statusCode + ", Title : " + inputName + " not found, or user unauthorized to perform action"); } else if (statusCode.equals(500)) { final String errorDetail = JsonPath.read(returnMessage, ERROR_MESSAGE_PATH); results.put(RETURN_RESULT, " error Message : " + errorDetail); results.put(EXCEPTION, " statusCode : " + statusCode + ", Title : message " + errorDetail); } else { results.put(RETURN_RESULT, throwable); results.put(EXCEPTION, throwable); } return results; }
Example #10
Source File: SolrFacetPivotDataReader.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
@Override protected Object getJSONPathValue(Object o, String jsonPathValue) throws JSONException { // can be an array with a single value, a single object or also null (not found) Object res = null; try { if (jsonPathValue.contains(" ")) { String initial = "$."; jsonPathValue = jsonPathValue.substring(jsonPathValue.indexOf("$") + 2); jsonPathValue = "['" + jsonPathValue + "']"; res = JsonPath.read(o, initial.concat(jsonPathValue)); } else { res = JsonPath.read(o, jsonPathValue); } } catch (PathNotFoundException e) { logger.debug("JPath not found " + jsonPathValue); } return res; }
Example #11
Source File: ServiceIntegrationTest.java From tutorials with MIT License | 6 votes |
@Test public void givenStructure_whenRequestingHighestRevenueMovieTitle_thenSucceed() { DocumentContext context = JsonPath.parse(jsonString); List<Object> revenueList = context.read("$[*]['box office']"); Integer[] revenueArray = revenueList.toArray(new Integer[0]); Arrays.sort(revenueArray); int highestRevenue = revenueArray[revenueArray.length - 1]; Configuration pathConfiguration = Configuration.builder() .options(Option.AS_PATH_LIST) .build(); List<String> pathList = JsonPath.using(pathConfiguration) .parse(jsonString) .read("$[?(@['box office'] == " + highestRevenue + ")]"); Map<String, String> dataRecord = context.read(pathList.get(0)); String title = dataRecord.get("title"); assertEquals("Skyfall", title); }
Example #12
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 #13
Source File: InfoqHotProcessor.java From hot-crawler with MIT License | 6 votes |
protected void getJson(){ try { // selected 4 + recommend 24 + hot_day 8 indexJson = Jsoup.connect(HOT_API_URL_INDEX).ignoreContentType(true). headers(getHttpRequest().getHeader()).method(Connection.Method.GET).execute().body(); recommendJson = Jsoup.connect(HOT_API_URL_RECOMMEND).ignoreContentType(true). headers(getHttpRequest().getHeader()).requestBody(REQUEST_BODY).method(Connection.Method.POST).execute().body(); this.score = JsonPath.read(recommendJson, "$.data.[-1].score"); if (score != null && score > 0) { recommendJson2 = Jsoup.connect(HOT_API_URL_RECOMMEND).ignoreContentType(true). headers(getHttpRequest().getHeader()).requestBody(getHttpRequest().getRequestBody()).method(Connection.Method.POST).execute().body(); } } catch (IOException e) { log.error("Something error {}", e.getMessage(), e); } }
Example #14
Source File: JSONObjectTest.java From JSON-Java-unit-test with Apache License 2.0 | 6 votes |
/** * Populate a JSONArray from a JSONObject names() method. * Confirm that it contains the expected names. */ @Test public void jsonObjectNamesToJsonAray() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; JSONObject jsonObject = new JSONObject(str); JSONArray jsonArray = jsonObject.names(); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); }
Example #15
Source File: JSONPathDataReader.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
@SuppressWarnings("unchecked") protected List<Object> getItems(String data) { Object parsed = JsonPath.read(data, jsonPathItems); if (parsed == null) { throw new JSONPathDataReaderException(String.format("Items not found in %s with json path %s", data, jsonPathItems)); } // can be an array or a single object List<Object> parsedData; if (parsed instanceof List) { parsedData = (List<Object>) parsed; } else { parsedData = Arrays.asList(parsed); } return parsedData; }
Example #16
Source File: JsonSourceMapper.java From siddhi-map-json with Apache License 2.0 | 5 votes |
private Event processCustomEvent(ReadContext readContext) { Configuration conf = Configuration.defaultConfiguration(); Event event = new Event(streamAttributesSize); Object[] data = event.getData(); Object childObject = readContext.read(DEFAULT_ENCLOSING_ELEMENT); readContext = JsonPath.using(conf).parse(childObject); Gson gsonWithNull = new GsonBuilder().serializeNulls().create(); for (MappingPositionData mappingPositionData : this.mappingPositions) { int position = mappingPositionData.getPosition(); Object mappedValue; try { mappedValue = readContext.read(mappingPositionData.getMapping()); if (mappedValue == null) { data[position] = null; } else if (mappedValue instanceof Map) { data[position] = attributeConverter.getPropertyValue(gsonWithNull.toJson(mappedValue), streamAttributes.get(position).getType()); } else { data[position] = attributeConverter.getPropertyValue(mappedValue.toString(), streamAttributes.get(position).getType()); } } catch (PathNotFoundException e) { if (failOnMissingAttribute) { log.error("Json message " + childObject.toString() + " contains missing attributes. Hence dropping the message."); return null; } data[position] = null; } } return event; }
Example #17
Source File: OpenshiftAPIService.java From openshift-elasticsearch-plugin with Apache License 2.0 | 5 votes |
/** * Execute a LocalSubectAccessReview * * @param token a token to check * @param project the namespace to check against * @param verb the verb (e.g. view) * @param resource the resource (e.g. pods/log) * @param resourceAPIGroup the group of the resource being checked * @param scopes the scopes: * null - use token scopes * empty - remove scopes * list - an array of scopes * * @return true if the SAR is satisfied */ public boolean localSubjectAccessReview(final String token, final String project, final String verb, final String resource, final String resourceAPIGroup, final String [] scopes) { try (DefaultOpenShiftClient client = factory.buildClient(token)) { XContentBuilder payload = XContentFactory.jsonBuilder() .startObject() .field("kind","SubjectAccessReview") .field("apiVersion","authorization.openshift.io/v1") .field("verb", verb) .array("scopes", scopes); if(resource.startsWith("/")) { payload.field("isNonResourceURL", Boolean.TRUE) .field("path", resource); } else { payload.field("resourceAPIGroup", resourceAPIGroup) .field("resource", resource) .field("namespace", project); } payload.endObject(); Request request = new Request.Builder() .url(String.format("%sapis/authorization.openshift.io/v1/subjectaccessreviews", client.getMasterUrl(), project)) .header("Authorization", "Bearer " + token) .header(CONTENT_TYPE, APPLICATION_JSON) .header(ACCEPT, APPLICATION_JSON) .post(RequestBody.create(MediaType.parse(APPLICATION_JSON), payload.string())) .build(); log(request); Response response = client.getHttpClient().newCall(request).execute(); final String body = IOUtils.toString(response.body().byteStream()); log(response, body); if(response.code() != RestStatus.CREATED.getStatus()) { throw new ElasticsearchSecurityException("Unable to determine user's operations role", RestStatus.fromCode(response.code())); } return JsonPath.read(body, "$.allowed"); } catch (IOException e) { LOGGER.error("Error determining user's role", e); } return false; }
Example #18
Source File: ScriptValue.java From karate with MIT License | 5 votes |
public ScriptValue copy(boolean deep) { switch (type) { case NULL: case UNKNOWN: case PRIMITIVE: case STRING: case BYTE_ARRAY: case INPUT_STREAM: case FEATURE: case JS_FUNCTION: case JAVA_FUNCTION: return this; case XML: String xml = XmlUtils.toString(getValue(Node.class)); return new ScriptValue(XmlUtils.toXmlDoc(xml)); case JSON: String json = getValue(DocumentContext.class).jsonString(); return new ScriptValue(JsonPath.parse(json)); case MAP: if (deep) { Map mapSource = getValue(Map.class); String strSource = JsonPath.parse(mapSource).jsonString(); Map mapDest = JsonPath.parse(strSource).read("$"); // only care about JS functions for treating specially retainRootKeyValuesWhichAreFunctions(mapSource, mapDest, false); return new ScriptValue(mapDest); } else { return new ScriptValue(new LinkedHashMap(getValue(Map.class))); } case LIST: if (deep) { String strList = getAsJsonDocument().jsonString(); return new ScriptValue(JsonPath.parse(strList)); } else { return new ScriptValue(new ArrayList(getValue(List.class))); } default: return this; } }
Example #19
Source File: JsonPathFilter.java From streams with Apache License 2.0 | 5 votes |
@Override public void prepare(Object configurationObject) { if ( configurationObject instanceof Map) { Map<String,String> params = ( Map<String,String>) configurationObject; pathExpression = params.get("pathExpression"); jsonPath = JsonPath.compile(pathExpression); destNodeName = pathExpression.substring(pathExpression.lastIndexOf(".") + 1); } }
Example #20
Source File: MimeTypeConverterTest.java From zerocode with Apache License 2.0 | 5 votes |
@Test public void testJsonArrayBlockToJson() throws Exception { String jsonBlockString = "{\n" + " \"addresses\": {\n" + " \"address\": [\n" + " {\n" + " \"postCode\": 4005,\n" + " \"message\": \"The field 'quantity' is invalid.\"\n" + " },\n" + " {\n" + " \"postCode\": 500,\n" + " \"message\": \"new message\"\n" + " }\n" + " ]\n" + " }\n" + " }"; String jsonArrayString = JsonPath.read(jsonBlockString, "$.addresses.address").toString(); System.out.println("--- jsonArray: \n" + jsonArrayString); JsonNode jsonNodeInput = mapper.readTree(jsonArrayString); Object jsonNodeOutput = xmlToJsonConverter.jsonBlockToJson(jsonNodeInput); System.out.println("--- jsonArrayBlockOutput:\n" + jsonNodeOutput); assertThat(jsonNodeOutput.toString(), containsString("[{\"postCode\":4005")); }
Example #21
Source File: JsonPathEvaluator.java From localization_nifi with Apache License 2.0 | 5 votes |
static JsonPath compileJsonPathExpression(String exp) { try { return JsonPath.compile(exp); } catch (Exception e) { throw new AttributeExpressionLanguageException("Invalid JSON Path expression: " + exp, e); } }
Example #22
Source File: AbstractJsonPathProcessor.java From localization_nifi with Apache License 2.0 | 5 votes |
@Override public ValidationResult validate(final String subject, final String input, final ValidationContext context) { String error = null; if (isStale(subject, input)) { if (JsonPathExpressionValidator.isValidExpression(input)) { JsonPath compiledJsonPath = JsonPath.compile(input); cacheComputedValue(subject, input, compiledJsonPath); } else { error = "specified expression was not valid: " + input; } } return new ValidationResult.Builder().subject(subject).valid(error == null).explanation(error).build(); }
Example #23
Source File: ServiceIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenId_whenRequestingRecordData_thenSucceed() { Object dataObject = JsonPath.parse(jsonString) .read("$[?(@.id == 2)]"); String dataString = dataObject.toString(); assertThat(dataString, containsString("2")); assertThat(dataString, containsString("Quantum of Solace")); assertThat(dataString, containsString("Twenty-second James Bond movie")); }
Example #24
Source File: ConverterV1Test.java From galeb with Apache License 2.0 | 5 votes |
private void convertFrom(State state) { String jsonStr = convertToString(state); if (jsonStr != null) { int numVirtualhosts = ((JSONArray) JsonPath.read(jsonStr, "$.virtualhosts[*]")).size(); IntStream.range(0, numVirtualhosts).forEach(pos -> { String virtualhostName = JsonPath.read(jsonStr, "$.virtualhosts[" + pos + "].name"); long numTargetsOrigin = states.get(state).stream().filter(line -> virtualhostName.equals(line[2]) && (converterV1.get(state).canSendTargetToRoute((String)line[16]))).count(); long numTargetsJson = ((JSONArray) JsonPath.read(jsonStr, "$.virtualhosts[" + pos + "].rules[*].pool.targets[*]")).size(); Assert.assertEquals("virtualhost " + virtualhostName + " target count problem", numTargetsOrigin, numTargetsJson); }); } }
Example #25
Source File: OperationIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { String jsonpathCreatorNamePath = "$['tool']['jsonpath']['creator']['name']"; String jsonpathCreatorLocationPath = "$['tool']['jsonpath']['creator']['location'][*]"; DocumentContext jsonContext = JsonPath.parse(jsonDataSourceString); String jsonpathCreatorName = jsonContext.read(jsonpathCreatorNamePath); List<String> jsonpathCreatorLocation = jsonContext.read(jsonpathCreatorLocationPath); assertEquals("Jayway Inc.", jsonpathCreatorName); assertThat(jsonpathCreatorLocation.toString(), containsString("Malmo")); assertThat(jsonpathCreatorLocation.toString(), containsString("San Francisco")); assertThat(jsonpathCreatorLocation.toString(), containsString("Helsingborg")); }
Example #26
Source File: CertificateGetTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void getCertificateCredentials_returnsWithCertificateAuthorityField() throws Exception { generateCa(mockMvc, "my-certificate", ALL_PERMISSIONS_TOKEN); final String response = getCertificateCredentialsByName(mockMvc, ALL_PERMISSIONS_TOKEN, "my-certificate"); final List<Boolean> values = JsonPath.parse(response) .read("$.certificates[*].versions[*].certificate_authority"); assertThat(values, hasSize(1)); assertThat(values.get(0), is(true)); }
Example #27
Source File: CertificateGetTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void getCertificateVersionsByCredentialId_returnsAllVersionsOfTheCertificateCredential() throws Exception { final String firstResponse = generateCertificateCredential(mockMvc, "/first-certificate", true, "test", null, ALL_PERMISSIONS_TOKEN); final String secondResponse = generateCertificateCredential(mockMvc, "/first-certificate", true, "test", null, ALL_PERMISSIONS_TOKEN); final String firstVersion = JsonPath.parse(firstResponse).read("$.id"); final String secondVersion = JsonPath.parse(secondResponse).read("$.id"); final String response = getCertificateCredentialsByName(mockMvc, ALL_PERMISSIONS_TOKEN, "/first-certificate"); final String certificateId = JsonPath.parse(response).read("$.certificates[0].id"); final MockHttpServletRequestBuilder getVersions = get("/api/v1/certificates/" + certificateId + "/versions") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON); final String responseVersion = mockMvc.perform(getVersions) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); final List<Map<String, String>> certificates = JsonPath.parse(responseVersion).read("$"); assertThat(certificates, hasSize(2)); assertThat(certificates.get(0).get("id"), containsString(secondVersion)); assertThat(certificates.get(1).get("id"), containsString(firstVersion)); }
Example #28
Source File: AlexaResponse.java From alexa-skills-kit-tester-java with Apache License 2.0 | 5 votes |
/** * Validates a custom json-path expression * @param jsonPathExpression a json-path expression * @return True, if expression returns an element */ public boolean is(String jsonPathExpression) { final String conditionalText = String.format("%1$s is TRUE.", jsonPathExpression); // turn simplified into valid JSONPath expression if (!jsonPathExpression.startsWith("?(@.")) { jsonPathExpression = "?(@." + jsonPathExpression + ")"; } // wrap validation expression final String jsonPath = "$.response[" + jsonPathExpression + "]"; // wrap response payload final Object o = JsonPath.using(config).parse("{ \"response\" : [ " + responsePayload + " ]}").read(jsonPath); // validate expression return result(o != null && o instanceof JSONArray && !((JSONArray)o).isEmpty(), conditionalText); }
Example #29
Source File: TrackerMetricsProvider.java From incubator-heron with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private Collection<Measurement> parse(String response, String component, String metric) { Collection<Measurement> metricsData = new ArrayList(); DocumentContext result = JsonPath.parse(response); JSONArray jsonArray = result.read("$.." + metric); if (jsonArray.size() != 1) { LOG.info(String.format("Did not get any metrics from tracker for %s:%s ", component, metric)); return metricsData; } Map<String, Object> metricsMap = (Map<String, Object>) jsonArray.get(0); if (metricsMap == null || metricsMap.isEmpty()) { LOG.info(String.format("Did not get any metrics from tracker for %s:%s ", component, metric)); return metricsData; } for (String instanceName : metricsMap.keySet()) { Map<String, String> tmpValues = (Map<String, String>) metricsMap.get(instanceName); for (String timeStamp : tmpValues.keySet()) { Measurement measurement = new Measurement( component, instanceName, metric, Instant.ofEpochSecond(Long.parseLong(timeStamp)), Double.parseDouble(tmpValues.get(timeStamp))); metricsData.add(measurement); } } return metricsData; }
Example #30
Source File: LambdaEventUtil.java From fullstop with Apache License 2.0 | 5 votes |
static Optional<String> getFromJSON(final String json, final String... jsonPaths) { Optional<String> result = empty(); for (final String jsonPath : jsonPaths) { try { result = Optional.ofNullable(JsonPath.read(json, jsonPath)); if (result.isPresent()) { return result; } } catch (final JsonPathException ignored) { // DO NOTHING } } return result; }