com.jayway.jsonpath.ReadContext Java Examples

The following examples show how to use com.jayway.jsonpath.ReadContext. 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: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
private void validateServiceOneMetadata(ReadContext ctx) {
	assertThat(ctx.read("$.services[0].metadata.displayName", String.class)).isEqualTo("service display name");
	assertThat(ctx.read("$.services[0].metadata.imageUrl", String.class)).isEqualTo("image-uri");
	assertThat(ctx.read("$.services[0].metadata.longDescription", String.class)).isEqualTo("service long " +
			"description");
	assertThat(ctx.read("$.services[0].metadata.providerDisplayName", String.class)).isEqualTo("service provider " +
			"display name");
	assertThat(ctx.read("$.services[0].metadata.documentationUrl", String.class)).isEqualTo("service" +
			"-documentation-url");
	assertThat(ctx.read("$.services[0].metadata.supportUrl", String.class)).isEqualTo("service-support-url");
	assertThat(ctx.read("$.services[0].metadata.key1", String.class)).isEqualTo("value1");
	assertThat(ctx.read("$.services[0].metadata.key2", String.class)).isEqualTo("value2");
	assertThat(ctx.read("$.services[0].metadata.licenses[0]", String.class)).isEqualTo("license1");
	assertThat(ctx.read("$.services[0].metadata.licenses[1]", String.class)).isEqualTo("license2");
	assertThat(ctx.read("$.services[0].metadata.features[0]", String.class)).isEqualTo("hosting");
	assertThat(ctx.read("$.services[0].metadata.features[1]", String.class)).isEqualTo("scaling");
}
 
Example #2
Source File: UDFJson.java    From sylph with Apache License 2.0 6 votes vote down vote up
/**
 * @return json string or null
 */
@SuppressWarnings("unchecked")
public String eval(String jsonString, String pathString)
        throws IOException
{
    if (jsonString == null) {
        return null;
    }
    if (!pathString.startsWith("$")) {
        pathString = "$." + pathString;
    }
    ReadContext context = JsonPath.using(jsonConf).parse(jsonString);
    Object value = context.read(pathString);

    if (value == null) {
        return null;
    }
    else if (value instanceof String) {
        return (String) value;
    }
    else {
        return value.toString();
    }
}
 
Example #3
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
private void validateServiceOne(ReadContext ctx) {
	assertThat(ctx.read("$.services[0]", Object.class)).isNotNull();
	assertThat(ctx.read("$.services[0].id", String.class)).isEqualTo("service-one-id");
	assertThat(ctx.read("$.services[0].name", String.class)).isEqualTo("Service One");
	assertThat(ctx.read("$.services[0].description", String.class)).isEqualTo("Description for Service One");
	assertThat(ctx.read("$.services[0].bindable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].bindings_retrievable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].allow_context_updates", Boolean.class)).isEqualTo(false);
	assertThat(ctx.read("$.services[0].instances_retrievable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plan_updateable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].requires[0]", String.class)).isEqualTo("syslog_drain");
	assertThat(ctx.read("$.services[0].requires[1]", String.class)).isEqualTo("route_forwarding");
	assertThat(ctx.read("$.services[0].tags[0]", String.class)).isEqualTo("tag1");
	assertThat(ctx.read("$.services[0].tags[1]", String.class)).isEqualTo("tag2");
	assertThat(ctx.read("$.services[0].dashboard_client.id", String.class)).isEqualTo("dashboard-id");
	assertThat(ctx.read("$.services[0].dashboard_client.secret", String.class)).isEqualTo("dashboard-secret");
	assertThat(ctx.read("$.services[0].dashboard_client.redirect_uri", String.class)).isEqualTo("dashboard" +
			"-redirect-uri");
}
 
Example #4
Source File: JsonParser.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
private String parseString(ReadContext source, String rule) {
    if (!rule.contains("{$.")) {
        try {
            return StringUtils.join("\n", ListUtils.toStringList(source.read(rule)));
        } catch (Exception e) {
            Logger.e(TAG, rule, e);
        }
        return "";
    } else {
        String result = rule;
        Matcher matcher = PATTERN_JSON.matcher(rule);
        while (matcher.find()) {
            final String group = matcher.group();
            final String string = parseString(source, group);
            result = result.replace(String.format("{%s}", group), string);
        }
        return result;
    }
}
 
Example #5
Source File: JsonParser.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
private List<String> parseStringList(ReadContext source, String rule) {
    if (!rule.contains("{$.")) {
        try {
            return ListUtils.toStringList(source.read(rule));
        } catch (Exception e) {
            Logger.e(TAG, rule, e);
        }
        return ListUtils.mutableList();
    } else {
        final List<String> resultList = new ArrayList<>();
        Matcher matcher = PATTERN_JSON.matcher(rule);
        while (matcher.find()) {
            final String group = matcher.group();
            final List<String> stringList = parseStringList(source, group);
            for (String string : stringList) {
                resultList.add(rule.replace(String.format("{%s}", group), string));
            }
        }
        return resultList;
    }
}
 
Example #6
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
private void validateServiceOneMetadata(ReadContext ctx) {
	assertThat(ctx.read("$.services[0].metadata.displayName", String.class)).isEqualTo("service display name");
	assertThat(ctx.read("$.services[0].metadata.imageUrl", String.class)).isEqualTo("image-uri");
	assertThat(ctx.read("$.services[0].metadata.longDescription", String.class)).isEqualTo("service long " +
			"description");
	assertThat(ctx.read("$.services[0].metadata.providerDisplayName", String.class)).isEqualTo("service provider " +
			"display name");
	assertThat(ctx.read("$.services[0].metadata.documentationUrl", String.class)).isEqualTo("service" +
			"-documentation-url");
	assertThat(ctx.read("$.services[0].metadata.supportUrl", String.class)).isEqualTo("service-support-url");
	assertThat(ctx.read("$.services[0].metadata.key1", String.class)).isEqualTo("value1");
	assertThat(ctx.read("$.services[0].metadata.key2", String.class)).isEqualTo("value2");
	assertThat(ctx.read("$.services[0].metadata.licenses[0]", String.class)).isEqualTo("license1");
	assertThat(ctx.read("$.services[0].metadata.licenses[1]", String.class)).isEqualTo("license2");
	assertThat(ctx.read("$.services[0].metadata.features[0]", String.class)).isEqualTo("hosting");
	assertThat(ctx.read("$.services[0].metadata.features[1]", String.class)).isEqualTo("scaling");
}
 
Example #7
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
private void validateServiceOne(ReadContext ctx) {
	assertThat(ctx.read("$.services[0]", Object.class)).isNotNull();
	assertThat(ctx.read("$.services[0].id", String.class)).isEqualTo("service-one-id");
	assertThat(ctx.read("$.services[0].name", String.class)).isEqualTo("Service One");
	assertThat(ctx.read("$.services[0].description", String.class)).isEqualTo("Description for Service One");
	assertThat(ctx.read("$.services[0].bindable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].bindings_retrievable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].allow_context_updates", Boolean.class)).isEqualTo(false);
	assertThat(ctx.read("$.services[0].instances_retrievable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plan_updateable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].requires[0]", String.class)).isEqualTo("syslog_drain");
	assertThat(ctx.read("$.services[0].requires[1]", String.class)).isEqualTo("route_forwarding");
	assertThat(ctx.read("$.services[0].tags[0]", String.class)).isEqualTo("tag1");
	assertThat(ctx.read("$.services[0].tags[1]", String.class)).isEqualTo("tag2");
	assertThat(ctx.read("$.services[0].dashboard_client.id", String.class)).isEqualTo("dashboard-id");
	assertThat(ctx.read("$.services[0].dashboard_client.secret", String.class)).isEqualTo("dashboard-secret");
	assertThat(ctx.read("$.services[0].dashboard_client.redirect_uri", String.class)).isEqualTo("dashboard" +
			"-redirect-uri");
}
 
Example #8
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
void fullCatalog() {
	String body = this.client.get().uri("/v2/catalog")
			.exchange()
			.expectStatus().isOk()
			.expectBody(String.class)
			.returnResult()
			.getResponseBody();

	assertThat(body).isNotNull();
	ReadContext ctx = JsonPath.parse(body);
	assertThat(ctx.read("$.services", List.class)).isNotEmpty();
	validateServiceOne(ctx);
	validateServiceOneMetadata(ctx);
	validateServiceOnePlans(ctx);
	validateServiceTwo(ctx);
}
 
Example #9
Source File: UserServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private HashMap<String, String> getUserProfileAttrs(Map<String, String> userProfileMapping, String userInfo) {
    TemplateEngine templateEngine = TemplateEngine.templateEngine();
    templateEngine.getTemplateContext().setVariable(TEMPLATE_ENGINE_PROFILE_ATTRIBUTE, userInfo);

    ReadContext userInfoPath = JsonPath.parse(userInfo);
    HashMap<String, String> map = new HashMap<>(userProfileMapping.size());

    for (Map.Entry<String, String> entry : userProfileMapping.entrySet()) {
        String field = entry.getKey();
        String mapping = entry.getValue();

        if (mapping != null) {
            try {
                if (mapping.contains("{#")) {
                    map.put(field, templateEngine.getValue(mapping, String.class));
                } else {
                    map.put(field, userInfoPath.read(mapping, String.class));
                }
            } catch (Exception e) {
                LOGGER.error("Using mapping: \"{}\", no fields are located in {}", mapping, userInfo);
            }
        }
    }

    return map;
}
 
Example #10
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private Map<String, String> extractUserProfileAttributes(Map<String, String> userProfileMapping, String userInfo) {
    TemplateEngine templateEngine = TemplateEngine.templateEngine();
    templateEngine.getTemplateContext().setVariable(TEMPLATE_ENGINE_PROFILE_ATTRIBUTE, userInfo);

    ReadContext userInfoPath = JsonPath.parse(userInfo);
    HashMap<String, String> map = new HashMap<>(userProfileMapping.size());

    for (Map.Entry<String, String> entry : userProfileMapping.entrySet()) {
        String field = entry.getKey();
        String mapping = entry.getValue();

        if (mapping != null && !mapping.isEmpty()) {
            try {
                if (mapping.contains("{#")) {
                    map.put(field, templateEngine.convert(mapping));
                } else {
                    map.put(field, userInfoPath.read(mapping).toString());
                }
            } catch (Exception e) {
                LOGGER.warn("Using mapping: \"{}\", no fields are located in {}", mapping, userInfo);
            }
        }
    }

    return map;
}
 
Example #11
Source File: use-add-on-data.7.x.java    From api-snippets with MIT License 6 votes vote down vote up
@RequestMapping(value = "/recording",
        produces = "application/xml",
        consumes = "application/json",
        method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<String> callback(@RequestParam("AddOns") String addOns) throws UnirestException {
    // If the Watson Speech to Text add-on found nothing, return immediately
    ReadContext addonsContext = JsonPath.parse(addOns);
    Map<String, Object> results = addonsContext.read("$.results");
    if(!results.containsKey("ibm_watson_speechtotext")) {
        return new ResponseEntity<>(
                "Add Watson Speech to Text add-on in your Twilio console", HttpStatus.OK);
    }

    // Retrieve the Watson Speech to Text add-on results
    String payloadUrl = addonsContext.read("$.results['ibm_watson_speechtotext'].payload[0].url");
    HttpResponse<String> response = Unirest
            .get(payloadUrl)
            .basicAuth(ACCOUNT_SID, AUTH_TOKEN)
            .asString();

    DocumentContext speechToTextContext = JsonPath.parse(response.getBody());
    List<String> transcripts = speechToTextContext
            .read("$.results[0].results[*].alternatives[0].transcript");

    return new ResponseEntity<>(String.join("", transcripts), HttpStatus.OK);
}
 
Example #12
Source File: ApiSteps.java    From akita with Apache License 2.0 6 votes vote down vote up
/**
 * В json строке, сохраннённой в переменной, происходит поиск значений по jsonpath из первого столбца таблицы.
 * Полученные значения сохраняются в переменных. Название переменной указывается во втором столбце таблицы.
 * Шаг работает со всеми типами json элементов: объекты, массивы, строки, числа, литералы true, false и null.
 */
@Тогда("^значения из json (?:строки|файла) \"([^\"]*)\", найденные по jsonpath из таблицы, сохранены в переменные$")
@Then("^values from json (?:string|file) named \"([^\"]*)\" has been found via jsonpaths from the table and saved to the variables$")
public void getValuesFromJsonAsString(String jsonVar, DataTable dataTable) {
    String strJson = loadValueFromFileOrPropertyOrVariableOrDefault(jsonVar);
    Gson gsonObject = new Gson();
    ReadContext ctx = JsonPath.parse(strJson, createJsonPathConfiguration());
    boolean error = false;
    for (List<String> row : dataTable.raw()) {
        String jsonPath = row.get(0);
        String varName = row.get(1);
        JsonElement jsonElement;
        try {
            jsonElement = gsonObject.toJsonTree(ctx.read(jsonPath));
        } catch (PathNotFoundException e) {
            error = true;
            continue;
        }
        akitaScenario.setVar(varName, jsonElement.toString());
        akitaScenario.write("JsonPath: " + jsonPath + ", значение: " + jsonElement + ", записано в переменную: " + varName);
    }
    if (error)
        throw new RuntimeException("В json не найдено значение по заданному jsonpath");
}
 
Example #13
Source File: ApiSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * В json строке, сохраннённой в переменной, происходит поиск значений по jsonpath из первого столбца таблицы.
 * Полученные значения сравниваются с ожидаемым значением во втором столбце таблицы.
 * Шаг работает со всеми типами json элементов: объекты, массивы, строки, числа, литералы true, false и null.
 */
@Тогда("^в json (?:строке|файле) \"([^\"]*)\" значения, найденные по jsonpath, равны значениям из таблицы$")
@Then("^values from json (?:string|file) named \"([^\"]*)\" found via jsonpath are equal to the values from the table$")
public void checkValuesInJsonAsString(String jsonVar, DataTable dataTable) {
    String strJson = loadValueFromFileOrPropertyOrVariableOrDefault(jsonVar);
    Gson gsonObject = new Gson();
    JsonParser parser = new JsonParser();
    ReadContext ctx = JsonPath.parse(strJson, createJsonPathConfiguration());
    boolean error = false;
    for (List<String> row : dataTable.raw()) {
        String jsonPath = row.get(0);
        JsonElement actualJsonElement;
        try {
            actualJsonElement = gsonObject.toJsonTree(ctx.read(jsonPath));
        } catch (PathNotFoundException e) {
            error = true;
            continue;
        }
        JsonElement expectedJsonElement = parser.parse(row.get(1));
        if (!actualJsonElement.equals(expectedJsonElement)) {
            error = true;
        }
        akitaScenario.write("JsonPath: " + jsonPath + ", ожидаемое значение: " + expectedJsonElement + ", фактическое значение: " + actualJsonElement);
    }
    if (error)
        throw new RuntimeException("Ожидаемые и фактические значения в json не совпадают");
}
 
Example #14
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
void fullCatalog() {
	String body = this.rest.getForObject("/v2/catalog", String.class);

	assertThat(body).isNotNull();
	ReadContext ctx = JsonPath.parse(body);
	assertThat(ctx.read("$.services", List.class)).isNotEmpty();
	validateServiceOne(ctx);
	validateServiceOneMetadata(ctx);
	validateServiceOnePlans(ctx);
	validateServiceTwo(ctx);
}
 
Example #15
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
private void validateServiceTwo(ReadContext ctx) {
	assertThat(ctx.read("$.services[1].id", String.class)).isEqualTo("service-two-id");
	assertThat(ctx.read("$.services[1].name", String.class)).isEqualTo("Service Two");
	assertThat(ctx.read("$.services[1].description", String.class)).isEqualTo("Description for Service Two");
	assertThat(ctx.read("$.services[1].plans[0].id", String.class)).isEqualTo("plan-one-id");
	assertThat(ctx.read("$.services[1].plans[0].name", String.class)).isEqualTo("Plan One");
	assertThat(ctx.read("$.services[1].plans[0].description", String.class)).isEqualTo("Description for Plan One");
}
 
Example #16
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
private void validateServiceTwo(ReadContext ctx) {
	assertThat(ctx.read("$.services[1].id", String.class)).isEqualTo("service-two-id");
	assertThat(ctx.read("$.services[1].name", String.class)).isEqualTo("Service Two");
	assertThat(ctx.read("$.services[1].description", String.class)).isEqualTo("Description for Service Two");
	assertThat(ctx.read("$.services[1].plans[0].id", String.class)).isEqualTo("plan-one-id");
	assertThat(ctx.read("$.services[1].plans[0].name", String.class)).isEqualTo("Plan One");
	assertThat(ctx.read("$.services[1].plans[0].description", String.class)).isEqualTo("Description for Plan One");
}
 
Example #17
Source File: JsonUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromJson() {
    //given
    String json = "{\"brand\":null,\"doors\":0,\"foo\":\"blablabla\"}";
    
    //when
    ReadContext readContext = JsonUtils.fromJson(json);
    
    //then
    assertThat(readContext, not(nullValue()));
    assertThat(readContext.read("$.foo"), equalTo("blablabla"));
}
 
Example #18
Source File: JsonSourceMapper.java    From siddhi-map-json with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: BookStoreIntegrationTests.java    From bookstore-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void bookIsDeleted() {
	BookStore bookStore = service.getBookStore(bookStoreId).block();
	assertThat(bookStore).isNotNull();
	Book book = bookStore.getBooks().get(0);
	assertThat(book).isNotNull();

	client.delete().uri("/bookstores/{bookStoreId}/books/{bookId}", bookStore.getId(), book.getId())
			.exchange()
			.expectStatus().isOk()
			.expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)
			.expectBody(String.class)
			.consumeWith(result -> {
				String body = result.getResponseBody();
				assertThat(body).isNotNull();
				ReadContext ctx = JsonPath.parse(body);
				assertThat(ctx.read("$.isbn", String.class)).isEqualTo(book.getIsbn());
				assertThat(ctx.read("$.links", Collection.class)).hasSize(1);
				assertThat(ctx.read("$.links[0].href", String.class))
						.endsWith(buildBookRef(bookStore.getId(), book.getId()));
				assertThat(ctx.read("$.links[0].rel", String.class)).isEqualTo(IanaLinkRelations.SELF.value());
			});

	BookStore updatedBookStore = service.getBookStore(bookStoreId).block();
	assertThat(updatedBookStore).isNotNull();
	assertThat(updatedBookStore.getBooks()).size().isEqualTo(1);
}
 
Example #20
Source File: BookStoreIntegrationTests.java    From bookstore-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void bookIsAdded() {
	BookStore bookStore = service.getBookStore(bookStoreId).block();
	assertThat(bookStore).isNotNull();

	client.put().uri("/bookstores/{bookStoreId}/books", bookStore.getId())
			.contentType(MediaType.APPLICATION_JSON)
			.accept(MediaType.APPLICATION_JSON)
			.bodyValue(
					"{\"isbn\":\"978-1785284151\", \"title\":\"Spring Boot Cookbook\", \"author\":\"Alex Antonov\"}")
			.exchange()
			.expectStatus().isCreated()
			.expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)
			.expectBody(String.class)
			.consumeWith(result -> {
				String body = result.getResponseBody();
				assertThat(body).isNotNull();
				ReadContext ctx = JsonPath.parse(body);
				assertThat(ctx.read("$.isbn", String.class)).isEqualTo("978-1785284151");
				assertThat(ctx.read("$.links", Collection.class)).hasSize(1);
				assertThat(ctx.read("$.links[0].href", String.class)).contains(buildBookRef(bookStore.getId()));
				assertThat(ctx.read("$.links[0].rel", String.class)).isEqualTo(IanaLinkRelations.SELF.value());
			});

	BookStore updatedBokStore = service.getBookStore(bookStoreId).block();
	assertThat(updatedBokStore).isNotNull();
	assertThat(updatedBokStore.getBooks()).size().isEqualTo(3);
}
 
Example #21
Source File: BookStoreIntegrationTests.java    From bookstore-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void bookIsRetrieved() {
	BookStore bookStore = service.getBookStore(bookStoreId).block();
	assertThat(bookStore).isNotNull();
	List<Book> books = bookStore.getBooks();
	Book book = books.get(0);
	assertThat(book).isNotNull();

	client.get().uri("/bookstores/{bookStoreId}/books/{bookId}", bookStore.getId(), book.getId())
			.exchange()
			.expectStatus().isOk()
			.expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)
			.expectBody(String.class)
			.consumeWith(result -> {
				String body = result.getResponseBody();
				assertThat(body).isNotNull();
				ReadContext ctx = JsonPath.parse(body);
				assertThat(ctx.read("$.isbn", String.class)).isEqualTo(book.getIsbn());
				assertThat(ctx.read("$.links", Collection.class)).hasSize(1);
				assertThat(ctx.read("$.links[0].href", String.class))
						.endsWith(buildBookRef(bookStore.getId(), book.getId()));
				assertThat(ctx.read("$.links[0].rel", String.class)).isEqualTo(IanaLinkRelations.SELF.value());
			});

	BookStore updatedBokStore = service.getBookStore(bookStoreId).block();
	assertThat(updatedBokStore).isNotNull();
	assertThat(updatedBokStore.getBooks()).size().isEqualTo(2);
}
 
Example #22
Source File: BookStoreIntegrationTests.java    From bookstore-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void bookStoreIsRetrieved() {
	BookStore bookStore = service.getBookStore(bookStoreId).block();
	assertThat(bookStore).isNotNull();

	client.get().uri("/bookstores/{bookStoreId}", bookStore.getId())
			.accept(MediaType.APPLICATION_JSON)
			.exchange()
			.expectStatus().isOk()
			.expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)
			.expectBody(String.class)
			.consumeWith(result -> {
				String body = result.getResponseBody();
				assertThat(body).isNotNull();
				ReadContext ctx = JsonPath.parse(body);
				assertThat(ctx.read("$.books", Collection.class)).hasSize(2);
				assertThat(ctx.read("$.books[*].isbn", Collection.class)).hasSize(2)
						.containsExactlyInAnyOrder(bookStore.getBooks().get(0).getIsbn(),
								bookStore.getBooks().get(1).getIsbn());
				assertThat(ctx.read("$.books[*].links[*]", Collection.class)).hasSize(2);
				assertThat(ctx.read("$.books[*].links[*].href", Collection.class)).containsExactlyInAnyOrder(
						buildBookRef(bookStore.getId(), bookStore.getBooks().get(0).getId()),
						buildBookRef(bookStore.getId(), bookStore.getBooks().get(1).getId()));
				assertThat(ctx.read("$.links", Collection.class)).hasSize(1);
				assertThat(ctx.read("$.links[0].href", String.class))
						.endsWith(buildBookStoreRef(bookStore.getId()));
				assertThat(ctx.read("$.links[0].rel", String.class)).isEqualTo(IanaLinkRelations.SELF.value());
			});
}
 
Example #23
Source File: JsonUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentFromJson() throws InterruptedException {
    MatcherAssert.assertThat(t -> {
        //given
        String uuid = UUID.randomUUID().toString(); 
        String json = "{\"brand\":null,\"doors\":0,\"foo\":\"" + uuid + "\"}";
        
        //when
        ReadContext readContext = JsonUtils.fromJson(json);
        
        // then
        return readContext.read("$.foo").equals(uuid);
    }, new RunsInThreads<>(new AtomicInteger(), TestExtension.THREADS));
}
 
Example #24
Source File: JsonParser.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
private List<Object> parseList(ReadContext source, String rule) {
    if (TextUtils.isEmpty(rule)) {
        return ListUtils.mutableList();
    }
    try {
        return source.read(rule);
    } catch (Exception e) {
        Logger.e(TAG, rule, e);
    }
    return ListUtils.mutableList();
}
 
Example #25
Source File: JsonParser.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
ReadContext fromObject(Object source) {
    if (source == null) {
        return null;
    }
    if (source instanceof ReadContext) {
        return (ReadContext) source;
    } else if (source instanceof String) {
        return JsonPath.parse((String) source);//必须强转为String
    }
    return JsonPath.parse(source);
}
 
Example #26
Source File: JsonParser.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
String parseObject(Object source) {
    if (source == null) {
        return "";
    }

    final ReadContext context = fromObject(source);
    Object json = context.json();
    if (json instanceof List || json instanceof Map) {
        return context.jsonString();
    }

    return StringUtils.valueOf(json);
}
 
Example #27
Source File: RolesValidator.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validate() {

    if (!super.validate()) {
        return false;
    }

    boolean valid=true;

    if (this.content != null && this.content.length() > 0) {

        final ReadContext ctx = JsonPath.parse(this.content.utf8ToString());
        final List<String> maskedFields = ctx.read("$..masked_fields[*]");

        if (maskedFields != null) {

            for (String mf : maskedFields) {
                if (!validateMaskedFieldSyntax(mf)) {
                    valid = false;
                }
            }
        }
    }

    if(!valid) {
       this.errorType = ErrorType.WRONG_DATATYPE;
    }

    return valid;
}
 
Example #28
Source File: FastJsonReader.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private ReadContext getReadContext() {
  return jsonReadContext;
}
 
Example #29
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
private void validateServiceOnePlans(ReadContext ctx) {
	assertThat(ctx.read("$.services[0].plans[0].id", String.class)).isEqualTo("plan-one-id");
	assertThat(ctx.read("$.services[0].plans[0].name", String.class)).isEqualTo("Plan One");
	assertThat(ctx.read("$.services[0].plans[0].description", String.class)).isEqualTo("Description for Plan One");
	assertThat(ctx.read("$.services[0].plans[0].maintenance_info.version", String.class)).isEqualTo("1.0.1");
	assertThat(ctx.read("$.services[0].plans[0].maintenance_info.description", String.class)).isEqualTo(
			"Description for maintenance info");
	assertThat(ctx.read("$.services[0].plans[1].id", String.class)).isEqualTo("plan-two-id");
	assertThat(ctx.read("$.services[0].plans[1].name", String.class)).isEqualTo("Plan Two");
	assertThat(ctx.read("$.services[0].plans[1].description", String.class)).isEqualTo("Description for Plan Two");
	assertThat(ctx.read("$.services[0].plans[1].metadata.displayName", String.class)).isEqualTo("sample display " +
			"name");
	assertThat(ctx.read("$.services[0].plans[1].metadata.bullets[0]", String.class)).isEqualTo("bullet1");
	assertThat(ctx.read("$.services[0].plans[1].metadata.bullets[1]", String.class)).isEqualTo("bullet2");
	assertThat(ctx.read("$.services[0].plans[1].metadata.costs[0].amount.usd", Number.class)).isEqualTo(649.0);
	assertThat(ctx.read("$.services[0].plans[1].metadata.costs[0].unit", String.class)).isEqualTo("MONTHLY");
	assertThat(ctx.read("$.services[0].plans[1].metadata.key1", String.class)).isEqualTo("value1");
	assertThat(ctx.read("$.services[0].plans[1].metadata.key2", String.class)).isEqualTo("value2");
	assertThat(ctx.read("$.services[0].plans[1].bindable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plans[1].free", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plans[1].plan_updateable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.$schema",
			String.class)).isEqualTo("http://json-schema.org/draft-04/schema#");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.type", String.class))
			.isEqualTo("string");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.enum[0]",
			String.class)).isEqualTo("one");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.enum[1]",
			String.class)).isEqualTo("two");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.enum[2]",
			String.class)).isEqualTo("three");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.update.parameters.$schema",
			String.class)).isEqualTo("http://json-schema.org/draft-04/schema#");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.update.parameters.type", String.class))
			.isEqualTo("object");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_binding.create.parameters.$schema",
			String.class)).isEqualTo("http://json-schema.org/draft-04/schema#");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_binding.create.parameters.type", String.class))
			.isEqualTo("object");
	assertThat(ctx.read("$.services[0].plans[1].maximum_polling_duration", Integer.class)).isEqualTo(120);
}
 
Example #30
Source File: CatalogControllerTest.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
private void validateServiceOnePlans(ReadContext ctx) {
	assertThat(ctx.read("$.services[0].plans[0].id", String.class)).isEqualTo("plan-one-id");
	assertThat(ctx.read("$.services[0].plans[0].name", String.class)).isEqualTo("Plan One");
	assertThat(ctx.read("$.services[0].plans[0].description", String.class)).isEqualTo("Description for Plan One");
	assertThat(ctx.read("$.services[0].plans[0].maintenance_info.version", String.class)).isEqualTo("1.0.1");
	assertThat(ctx.read("$.services[0].plans[0].maintenance_info.description", String.class)).isEqualTo(
			"Description for maintenance info");
	assertThat(ctx.read("$.services[0].plans[1].id", String.class)).isEqualTo("plan-two-id");
	assertThat(ctx.read("$.services[0].plans[1].name", String.class)).isEqualTo("Plan Two");
	assertThat(ctx.read("$.services[0].plans[1].description", String.class)).isEqualTo("Description for Plan Two");
	assertThat(ctx.read("$.services[0].plans[1].metadata.displayName", String.class)).isEqualTo("sample display " +
			"name");
	assertThat(ctx.read("$.services[0].plans[1].metadata.bullets[0]", String.class)).isEqualTo("bullet1");
	assertThat(ctx.read("$.services[0].plans[1].metadata.bullets[1]", String.class)).isEqualTo("bullet2");
	assertThat(ctx.read("$.services[0].plans[1].metadata.costs[0].amount.usd", Number.class)).isEqualTo(649.0);
	assertThat(ctx.read("$.services[0].plans[1].metadata.costs[0].unit", String.class)).isEqualTo("MONTHLY");
	assertThat(ctx.read("$.services[0].plans[1].metadata.key1", String.class)).isEqualTo("value1");
	assertThat(ctx.read("$.services[0].plans[1].metadata.key2", String.class)).isEqualTo("value2");
	assertThat(ctx.read("$.services[0].plans[1].bindable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plans[1].free", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plans[1].plan_updateable", Boolean.class)).isEqualTo(true);
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.$schema",
			String.class)).isEqualTo("http://json-schema.org/draft-04/schema#");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.type", String.class))
			.isEqualTo("string");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.enum[0]",
			String.class)).isEqualTo("one");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.enum[1]",
			String.class)).isEqualTo("two");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.create.parameters.enum[2]",
			String.class)).isEqualTo("three");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.update.parameters.$schema",
			String.class)).isEqualTo("http://json-schema.org/draft-04/schema#");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_instance.update.parameters.type", String.class))
			.isEqualTo("object");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_binding.create.parameters.$schema",
			String.class)).isEqualTo("http://json-schema.org/draft-04/schema#");
	assertThat(ctx.read("$.services[0].plans[1].schemas.service_binding.create.parameters.type", String.class))
			.isEqualTo("object");
	assertThat(ctx.read("$.services[0].plans[1].maximum_polling_duration", Integer.class)).isEqualTo(120);
}