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: 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 #3
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 #4
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 #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: 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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: FastJsonReader.java From pentaho-kettle with Apache License 2.0 | 5 votes |
private static JsonPath[] compilePaths( JsonInputField[] fields ) { JsonPath[] paths = new JsonPath[ fields.length ]; int i = 0; for ( JsonInputField field : fields ) { paths[ i++ ] = JsonPath.compile( field.getPath() ); } return paths; }
Example #19
Source File: HelperJsonUtils.java From zerocode with Apache License 2.0 | 5 votes |
public static Object readJsonPathOrElseNull(String requestJson, String jsonPath) { try { return JsonPath.read(requestJson, jsonPath); } catch (PathNotFoundException pEx) { LOGGER.debug("No " + jsonPath + " was present in the request. returned null."); return null; } }
Example #20
Source File: OperationIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class) .get("price") .toString()) > 20.00; List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString) .read("$['book'][?]", expensivePredicate); predicateUsageAssertionHelper(expensive); }
Example #21
Source File: AnalyzeByJSonPath.java From a with GNU General Public License v3.0 | 5 votes |
public AnalyzeByJSonPath parse(Object json) { if (json instanceof String) { ctx = JsonPath.parse((String) json); } else { ctx = JsonPath.parse(json); } return this; }
Example #22
Source File: JsonPathTest.java From java-master with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { File file = ResourceUtils.getFile("classpath:book.json"); DocumentContext documentContext = JsonPath.parse(file); Object object = documentContext.read("$"); System.out.println(object); object = documentContext.read("$.store.book[*].author"); System.out.println(object); object = documentContext.read("$..author"); System.out.println(object); object = documentContext.read("$.store.*"); System.out.println(object); object = documentContext.read("$.store..price"); System.out.println(object); object = documentContext.read("$..book[2]"); System.out.println(object); object = documentContext.read("$..book[-1:]"); System.out.println(object); object = documentContext.read("$..book[0,1]"); System.out.println(object); object = documentContext.read("$..book[?(@.isbn)]"); System.out.println(object); object = documentContext.read("$..book[?(@.price<10)]"); System.out.println(object); }
Example #23
Source File: JSONPathExtractor.java From web-data-extractor with Apache License 2.0 | 5 votes |
@Override public List<String> extractList(String data) { List<Object> list = JsonPath.using(conf).parse(data).read(jsonpath); List<String> stringList = new LinkedList<>(); for (Object one : list) { if (one instanceof Map) { JSONObject jsonObject = new JSONObject((Map<String, ?>) one); stringList.add(jsonObject.toJSONString()); } else { stringList.add(TypeUtils.castToString(one)); } } return stringList; }
Example #24
Source File: MvcIntegrationTestUtils.java From find with MIT License | 5 votes |
public String[] getFields(final MockMvc mockMvc, final String subPath, final String... fieldTypes) throws Exception { final MockHttpServletRequestBuilder requestBuilder = get(FieldsController.FIELDS_PATH + subPath) .with(authentication(userAuth())); requestBuilder.param(FieldsController.FIELD_TYPES_PARAM, fieldTypes); addFieldRequestParams(requestBuilder); final MvcResult mvcResult = mockMvc.perform(requestBuilder) .andReturn(); final Collection<Map<String, String>> tagNames = JsonPath.compile("$").read(mvcResult.getResponse().getContentAsString()); return tagNames.stream().map(tagName -> tagName.get("id")).toArray(String[]::new); }
Example #25
Source File: TestJsonPathRowRecordReader.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testElementWithNestedData() throws IOException, MalformedRecordException { final LinkedHashMap<String, JsonPath> jsonPaths = new LinkedHashMap<>(allJsonPaths); jsonPaths.put("account", JsonPath.compile("$.account")); final DataType accountType = RecordFieldType.RECORD.getRecordDataType(getAccountSchema()); final List<RecordField> fields = getDefaultFields(); fields.add(new RecordField("account", accountType)); final RecordSchema schema = new SimpleRecordSchema(fields); try (final InputStream in = new FileInputStream(new File("src/test/resources/json/single-element-nested.json")); final JsonPathRowRecordReader reader = new JsonPathRowRecordReader(jsonPaths, schema, in, Mockito.mock(ComponentLog.class), dateFormat, timeFormat, timestampFormat)) { final List<String> fieldNames = schema.getFieldNames(); final List<String> expectedFieldNames = Arrays.asList(new String[] {"id", "name", "balance", "address", "city", "state", "zipCode", "country", "account"}); assertEquals(expectedFieldNames, fieldNames); final List<RecordFieldType> dataTypes = schema.getDataTypes().stream().map(dt -> dt.getFieldType()).collect(Collectors.toList()); final List<RecordFieldType> expectedTypes = Arrays.asList(new RecordFieldType[] {RecordFieldType.INT, RecordFieldType.STRING, RecordFieldType.DOUBLE, RecordFieldType.STRING, RecordFieldType.STRING, RecordFieldType.STRING, RecordFieldType.STRING, RecordFieldType.STRING, RecordFieldType.RECORD}); assertEquals(expectedTypes, dataTypes); final Object[] firstRecordValues = reader.nextRecord().getValues(); final Object[] simpleElements = Arrays.copyOfRange(firstRecordValues, 0, firstRecordValues.length - 1); Assert.assertArrayEquals(new Object[] {1, "John Doe", null, "123 My Street", "My City", "MS", "11111", "USA"}, simpleElements); final Object lastElement = firstRecordValues[firstRecordValues.length - 1]; assertTrue(lastElement instanceof Record); final Record record = (Record) lastElement; assertEquals(42, record.getValue("id")); assertEquals(4750.89D, record.getValue("balance")); assertNull(reader.nextRecord()); } }
Example #26
Source File: AuthorizationServerConfigurationTest.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
private OAuth2AccessToken obtainAccessToken(String username, String password, boolean remove) throws Exception { OAuth2AccessToken oauthToken = null; try { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("grant_type", "password"); params.add("username", username); params.add("password", password); String hash = new String(Base64.encode("test1_consumer:secret".getBytes())); ResultActions result = mockMvc.perform(post("/oauth/token") .params(params) .header("Authorization", "Basic " + hash) .accept("application/json;charset=UTF-8")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")); String resultString = result.andReturn().getResponse().getContentAsString(); System.out.println(resultString); Assert.assertTrue(StringUtils.isNotBlank(resultString)); String token = JsonPath.parse(resultString).read("$.access_token"); Assert.assertTrue(StringUtils.isNotBlank(token)); Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username); Assert.assertEquals(1, oauthTokens.size()); oauthToken = oauthTokens.stream().findFirst().get(); Assert.assertEquals(token, oauthToken.getValue()); } catch (Exception e) { throw e; } finally { if (null != oauthToken && remove) { this.apiOAuth2TokenManager.removeAccessToken(oauthToken); } } return oauthToken; }
Example #27
Source File: JsonRecordParser.java From kafka-connect-zeebe with Apache License 2.0 | 5 votes |
/** * If given a string parse the JSON document, otherwise delegate to {@link JsonPath#parse(Object)} */ private DocumentContext parseDocument(final Object value) { if (value instanceof String) { return JsonPath.parse((String) value); } return JsonPath.parse(value); }
Example #28
Source File: HttpJmapAuthentication.java From james-project with Apache License 2.0 | 5 votes |
public static AccessToken doAuthenticate(URIBuilder uriBuilder, Username username, String password) throws ClientProtocolException, IOException, URISyntaxException { String continuationToken = getContinuationToken(uriBuilder, username); Response response = postAuthenticate(uriBuilder, password, continuationToken); return AccessToken.of( JsonPath.parse(response.returnContent().asString()) .read("accessToken")); }
Example #29
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; }
Example #30
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); }