下面列出了com.fasterxml.jackson.core.PrettyPrinter#com.jayway.jsonpath.DocumentContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void givenDirector_whenRequestingLatestMovieTitle_thenSucceed() {
DocumentContext context = JsonPath.parse(jsonString);
List<Map<String, Object>> dataList = context.read("$[?(@.director == 'Sam Mendes')]");
List<Object> dateList = new ArrayList<>();
for (Map<String, Object> item : dataList) {
Object date = item.get("release date");
dateList.add(date);
}
Long[] dateArray = dateList.toArray(new Long[0]);
Arrays.sort(dateArray);
long latestTime = dateArray[dateArray.length - 1];
List<Map<String, Object>> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]");
String title = (String) finalDataList.get(0)
.get("title");
assertEquals("Spectre", title);
}
private static void addDecryptedDataToPayload(DocumentContext payloadContext, String decryptedValue, String jsonPathOut) {
JsonProvider jsonProvider = jsonPathConfig.jsonProvider();
Object decryptedValueJsonElement = jsonEngine.parse(decryptedValue);
if (!jsonEngine.isJsonObject(decryptedValueJsonElement)) {
// Array or primitive: overwrite
payloadContext.set(jsonPathOut, decryptedValueJsonElement);
return;
}
// Object: merge
int length = jsonProvider.length(decryptedValueJsonElement);
Collection<String> propertyKeys = (0 == length) ? Collections.<String>emptyList() : jsonProvider.getPropertyKeys(decryptedValueJsonElement);
for (String key : propertyKeys) {
payloadContext.delete(jsonPathOut + "." + key);
payloadContext.put(jsonPathOut, key, jsonProvider.getMapValue(decryptedValueJsonElement, key));
}
}
public static DocumentContext toJsonDoc(ScriptValue sv, ScenarioContext context) {
if (sv.isJson()) { // optimize
return (DocumentContext) sv.getValue();
} else if (sv.isListLike()) {
return JsonPath.parse(sv.getAsList());
} else if (sv.isMapLike()) {
return JsonPath.parse(sv.getAsMap());
} else if (sv.isUnknown()) { // POJO
return JsonUtils.toJsonDoc(sv.getValue());
} else if (sv.isStringOrStream()) {
ScriptValue temp = evalKarateExpression(sv.getAsString(), context);
if (!temp.isJson()) {
throw new RuntimeException("cannot convert, not a json string: " + sv);
}
return temp.getValue(DocumentContext.class);
} else {
throw new RuntimeException("cannot convert to json: " + sv);
}
}
@Test
void test_nestedObjectType() {
DocumentContext document = parse(new JsonTemplate(
"@address : {city:@s, street:@s , number:@i}," +
"@person : @address{office, home}," +
"@person[](2)"));
assertThat(document.read("$[0].office.city", String.class), is(notNullValue()));
assertThat(document.read("$[0].office.street", String.class), is(notNullValue()));
assertThat(document.read("$[0].office.number", Integer.class), is(notNullValue()));
assertThat(document.read("$[0].home.city", String.class), is(notNullValue()));
assertThat(document.read("$[0].home.street", String.class), is(notNullValue()));
assertThat(document.read("$[0].home.number", Integer.class), is(notNullValue()));
assertThat(document.read("$[1].office.city", String.class), is(notNullValue()));
assertThat(document.read("$[1].office.street", String.class), is(notNullValue()));
assertThat(document.read("$[1].office.number", Integer.class), is(notNullValue()));
assertThat(document.read("$[1].home.city", String.class), is(notNullValue()));
assertThat(document.read("$[1].home.street", String.class), is(notNullValue()));
assertThat(document.read("$[1].home.number", Integer.class), is(notNullValue()));
}
@Test
void dashboardClientIsBuiltWithAllValues() {
DashboardClient client = DashboardClient.builder()
.id("client-id")
.secret("client-secret")
.redirectUri("https://token.app.local")
.build();
assertThat(client.getId()).isEqualTo("client-id");
assertThat(client.getSecret()).isEqualTo("client-secret");
assertThat(client.getRedirectUri()).isEqualTo("https://token.app.local");
DocumentContext json = JsonUtils.toJsonPath(client);
assertThat(json).hasPath("$.id").isEqualTo("client-id");
assertThat(json).hasPath("$.secret").isEqualTo("client-secret");
assertThat(json).hasPath("$.redirect_uri").isEqualTo("https://token.app.local");
}
@Then("^mailbox \"([^\"]*)\" contains (\\d+) messages$")
public void mailboxContainsMessages(String mailboxName, int messageCount) {
String username = userStepdefs.getConnectedUser();
String mailboxId = mainStepdefs.getMailboxId(username, mailboxName).serialize();
calmlyAwait.until(() -> {
String requestBody = "[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + mailboxId + "\"]}}, \"#0\"]]";
httpClient.post(requestBody);
assertThat(httpClient.response.getStatusLine().getStatusCode()).isEqualTo(200);
DocumentContext jsonPath = JsonPath.parse(httpClient.response.getEntity().getContent());
assertThat(jsonPath.<String>read(NAME)).isEqualTo("messageList");
return jsonPath.<List<String>>read(ARGUMENTS + ".messageIds").size() == messageCount;
});
}
@Override
public Integration apply(Integration integration) {
if (ObjectHelper.isEmpty(expression)) {
return integration;
}
try {
final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonProvider(JsonUtils.copyObjectMapperConfiguration()))
.mappingProvider(new JacksonMappingProvider(JsonUtils.copyObjectMapperConfiguration()))
.build();
DocumentContext json = JsonPath.using(configuration).parse(JsonUtils.writer().forType(Integration.class).writeValueAsString(integration));
if (ObjectHelper.isEmpty(key)) {
json.set(expression, value);
} else {
json.put(expression, key, value);
}
return JsonUtils.reader().forType(Integration.class).readValue(json.jsonString());
} catch (IOException e) {
throw new IllegalStateException("Failed to evaluate json path expression on integration object", e);
}
}
@Test
void test_objectInArrayType() {
DocumentContext document = parse(new JsonTemplate(
"@methods : {name:@s, paramCount:@i(min=0, max=5)}," +
"@classes : @methods[](2)," +
"@classes[](2)"));
assertThat(document.read("$.length()", Integer.class), is(2));
assertThat(document.read("$[0].length()", Integer.class), is(2));
assertThat(document.read("$[0].[0].name", String.class), is(notNullValue()));
assertThat(document.read("$[0].[0].paramCount", Integer.class), is(
both(greaterThanOrEqualTo(0)).and(lessThanOrEqualTo(5))));
assertThat(document.read("$[1].length()", Integer.class), is(2));
assertThat(document.read("$[1].[0].name", String.class), is(notNullValue()));
assertThat(document.read("$[1].[0].paramCount", Integer.class), is(
both(greaterThanOrEqualTo(0)).and(lessThanOrEqualTo(5))));
}
@Test
public void calendarAttachmentShouldBePublishedInMQWhenMatchingWorkflowConfiguration() throws Exception {
messageSender.connect(LOCALHOST_IP, jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpPort())
.sendMessage(FakeMail.builder()
.name("name")
.mimeMessage(messageWithICSAttached)
.sender(FROM)
.recipient(RECIPIENT));
testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
.login(RECIPIENT, PASSWORD)
.select(TestIMAPClient.INBOX)
.awaitMessage(awaitAtMostOneMinute);
Optional<String> content = amqpRule.readContent();
assertThat(content).isPresent();
DocumentContext jsonPath = toJsonPath(content.get());
assertThat(jsonPath.<String>read("ical")).isEqualTo(ICS_1);
assertThat(jsonPath.<String>read("sender")).isEqualTo(FROM);
assertThat(jsonPath.<String>read("recipient")).isEqualTo(RECIPIENT);
assertThat(jsonPath.<String>read("uid")).isEqualTo(ICS_UID);
assertThat(jsonPath.<String>read("sequence")).isEqualTo(ICS_SEQUENCE);
assertThat(jsonPath.<String>read("dtstamp")).isEqualTo(ICS_DTSTAMP);
assertThat(jsonPath.<String>read("method")).isEqualTo(ICS_METHOD);
assertThat(jsonPath.<String>read("recurrence-id")).isNull();
}
@Test
public void base64CalendarAttachmentShouldBePublishedInMQWhenMatchingWorkflowConfiguration() throws Exception {
messageSender.connect(LOCALHOST_IP, jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpPort())
.sendMessage(FakeMail.builder()
.name("name")
.mimeMessage(messageWithICSBase64Attached)
.sender(FROM)
.recipient(RECIPIENT));
testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
.login(RECIPIENT, PASSWORD)
.select(TestIMAPClient.INBOX)
.awaitMessage(awaitAtMostOneMinute);
Optional<String> content = amqpRule.readContent();
assertThat(content).isPresent();
DocumentContext jsonPath = toJsonPath(content.get());
assertThat(jsonPath.<String>read("sender")).isEqualTo(FROM);
assertThat(jsonPath.<String>read("recipient")).isEqualTo(RECIPIENT);
assertThat(jsonPath.<String>read("uid")).isEqualTo(ICS_BASE64_UID);
assertThat(jsonPath.<String>read("sequence")).isEqualTo(ICS_SEQUENCE);
assertThat(jsonPath.<String>read("dtstamp")).isEqualTo(ICS_BASE64_DTSTAMP);
assertThat(jsonPath.<String>read("method")).isEqualTo(ICS_METHOD);
assertThat(jsonPath.<String>read("recurrence-id")).isNull();
}
public void writeJSON( File target, DocumentContext contents ) throws ManipulationException
{
try
{
PrettyPrinter dpp = new MyPrettyPrinter( getCharset() );
ObjectMapper mapper = new ObjectMapper();
String jsonString = contents.jsonString();
String pretty = mapper.writer( dpp ).writeValueAsString( mapper.readValue( jsonString, Object.class ) );
Charset cs = getCharset();
FileOutputStream fileOutputStream = new FileOutputStream( target );
try (OutputStreamWriter p = new OutputStreamWriter( fileOutputStream, cs ) )
{
p.write( pretty );
p.append( getEOL() );
}
}
catch ( IOException e )
{
logger.error( "Unable to write JSON string: ", e );
throw new ManipulationException( "Unable to write JSON string", e );
}
}
@Test
public void testNonStrictJsonParsing() {
String raw = "{ foo: 'bar' }";
DocumentContext dc = JsonUtils.toJsonDoc(raw);
logger.debug("parsed json: {}", dc.jsonString());
String value = dc.read("$.foo");
assertEquals("bar", value);
}
@Test
public void testSimpleJsonMatch() {
ScenarioContext ctx = getContext();
DocumentContext doc = JsonUtils.toJsonDoc("{ foo: 'bar' }");
ctx.vars.put("json", doc);
assertFalse(Script.matchNamed(MatchType.EQUALS, "json", "$", "{ }", ctx).pass);
}
public JmsMessagePredicate newJmsMessagePredicate(String source, String testId, String messageBody){
Document xmlDocument = parseXml(messageBody);
if (xmlDocument != null) {
return new JmsXmlMessagePredicate(source, testId, xmlDocument);
}
DocumentContext jsonContext = parseJson(messageBody);
if (jsonContext != null){
return new JmsJsonMessagePredicate(source, testId, jsonContext);
}
return new JmsMessagePredicate(source, testId);
}
public static void verifyResourceDescriptors(File actualPath, File expectedPath, boolean strict) throws IOException, ParseException {
String actualText = readFile(actualPath);
String expectedText = readFile(expectedPath);
JsonTextMessageValidator validator = new JsonTextMessageValidator();
validator.setStrict(strict);
DocumentContext actualContext = JsonPath.parse(actualText);
validator.validateJson(newMessage(actualText),
newMessage(expectedText),
new JsonMessageValidationContext(),
createTestContext(),
actualContext);
}
private void responseWithStateIsSerializedToJson(OperationState stateValue, String stateString) {
GetLastServiceBindingOperationResponse response = GetLastServiceBindingOperationResponse.builder()
.operationState(stateValue)
.description("description")
.build();
DocumentContext json = JsonUtils.toJsonPath(response);
assertThat(json).hasPath("$.state").isEqualTo(stateString);
assertThat(json).hasPath("$.description").isEqualTo("description");
}
@Then("^\"([^\"]*)\" should be able to retrieve the content$")
public void contentShouldBeRetrievable(String username) throws Exception {
AccessToken accessToken = userStepdefs.authenticate(username);
DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
Request request = Request.Get(baseUri(mainStepdefs.jmapServer).setPath("/download/" + jsonPath.<String>read("blobId")).build());
if (accessToken != null) {
request.addHeader("Authorization", accessToken.asString());
}
response = request.execute().returnResponse();
httpAuthorizedStatus();
}
@Test
void test_typeWithListParam() {
DocumentContext document = parse(new JsonTemplate(
"@address:{city:@s(Amsterdam, Utrecht), street:@s, number:@i(5, 10, 15)}," +
"{office:@address, home:@address }"));
assertThat(document.read("$.office.city", String.class), isIn(new String[]{"Amsterdam", "Utrecht"}));
assertThat(document.read("$.office.street", String.class), is(notNullValue()));
assertThat(document.read("$.office.number", Integer.class), isIn(new Integer[]{5, 10, 15}));
assertThat(document.read("$.home.city", String.class), isIn(new String[]{"Amsterdam", "Utrecht"}));
assertThat(document.read("$.home.street", String.class), is(notNullValue()));
assertThat(document.read("$.home.number", Integer.class), isIn(new Integer[]{5, 10, 15}));
}
@Test
void responseWithDefaultsIsBuilt() {
CreateServiceInstanceRouteBindingResponse response = CreateServiceInstanceRouteBindingResponse.builder()
.build();
assertThat(response.isBindingExisted()).isEqualTo(false);
assertThat(response.getRouteServiceUrl()).isNull();
DocumentContext json = JsonUtils.toJsonPath(response);
assertThat(json).hasNoPath("$.route_service_url");
}
@Test
public void serializeWithCommentParameter() {
this.requestBuilder = SshParametersRequest.builder().name(new SimpleCredentialName("example", "credential"))
.overwrite(true).mode(WriteMode.CONVERGE).parameters(new SshParameters("ssh comment"));
DocumentContext json = toJsonPath(this.requestBuilder);
assertCommonRequestFields(json, true, WriteMode.CONVERGE, "/example/credential", "ssh");
JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_length");
JsonPathAssert.assertThat(json).hasPath("$.parameters.ssh_comment").isEqualTo("ssh comment");
}
private boolean matchesJsonPath(List<String> unmatchedJsonPath,
DocumentContext parsedJson, String jsonPath) {
try {
JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath);
return true;
}
catch (Exception e) {
unmatchedJsonPath.add(e.getLocalizedMessage());
return false;
}
}
private void responseWithStateIsSerializedToJson(OperationState stateValue, String stateString) {
GetLastServiceOperationResponse response = GetLastServiceOperationResponse.builder()
.operationState(stateValue)
.description("description")
.build();
DocumentContext json = JsonUtils.toJsonPath(response);
assertThat(json).hasPath("$.state").isEqualTo(stateString);
assertThat(json).hasPath("$.description").isEqualTo("description");
}
static DocumentContext validateAndEstablishJsonContext(ProcessSession processSession, FlowFile flowFile) {
// Parse the document once into an associated context to support multiple path evaluations if specified
final AtomicReference<DocumentContext> contextHolder = new AtomicReference<>(null);
processSession.read(flowFile, new InputStreamCallback() {
@Override
public void process(InputStream in) throws IOException {
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(in)) {
DocumentContext ctx = JsonPath.using(STRICT_PROVIDER_CONFIGURATION).parse(bufferedInputStream);
contextHolder.set(ctx);
}
}
});
return contextHolder.get();
}
@Test
@TestsNotMeantForZowe
public void shouldCallDiscoverableServiceApi() throws Exception {
// When
final HttpResponse response = HttpRequestUtils.getResponse("/api/v1/discoverableclient/greeting", SC_OK);
final String jsonResponse = EntityUtils.toString(response.getEntity());
DocumentContext jsonContext = JsonPath.parse(jsonResponse);
String content = jsonContext.read("$.content");
// Then
assertThat(content, equalTo("Hello, world!"));
}
private Object returnObjectForTest(TestSideRequestTemplateModel model,
String jsonPath) {
String body = removeSurroundingQuotes(model.getEscapedBody()).replace("\\\"",
"\"");
DocumentContext documentContext = JsonPath.parse(body);
Object value = documentContext.read(jsonPath);
return processTestResponseValue(value);
}
@Test
public void serializeWithNoParameters() {
this.requestBuilder = PasswordParametersRequest.builder()
.name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.NO_OVERWRITE);
DocumentContext json = toJsonPath(this.requestBuilder);
assertCommonRequestFields(json, true, WriteMode.NO_OVERWRITE, "/example/credential", "password");
assertParametersNotSet(json);
}
@Test
void test_arrayMixedType() {
DocumentContext document = parse(new JsonTemplate("{anArray:@s[1, @i(2), @b(false), @s(4)]}"));
assertThat(document.read("$.anArray.length()", Integer.class), is(4));
assertThat(document.read("$.anArray[0]", String.class), is("1"));
assertThat(document.read("$.anArray[1]", Integer.class), is(2));
assertThat(document.read("$.anArray[2]", Boolean.class), is(false));
assertThat(document.read("$.anArray[3]", String.class), is("4"));
}
private boolean allInstancesUp(DocumentContext documentContext) {
return documentContext.read("$.details.gateway.details.apicatalog").equals("UP")
&& documentContext.read("$.details.gateway.details.discovery").equals("UP")
&& documentContext.read("$.details.gateway.details.auth").equals("UP")
&& documentContext.read("$.details.gateway.details.gatewayCount")
.equals(gatewayConfiguration.getInstances());
}
@Test
public void generateAUserCredential_afterSettingTheCredential_whenTheParametersAreNull_overwritesTheCredential() throws Exception {
final String user = "userA";
final String password = "passwordA";
final MockHttpServletRequestBuilder setRequest = put("/api/v1/data")
.header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON_UTF8)
.content("{" +
"\"type\":\"user\"," +
"\"name\":\"" + credentialName1 + "\"," +
"\"value\": {\"username\":\"" + user + "\",\"password\":\"" + password + "\"} " +
"}");
mockMvc.perform(setRequest)
.andDo(print())
.andExpect(status().isOk());
final MockHttpServletRequestBuilder generateRequest = post("/api/v1/data")
.header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON_UTF8)
.content("{\"type\":\"user\",\"name\":\"" + credentialName1 + "\"}");
final DocumentContext response = JsonPath.parse(mockMvc.perform(generateRequest).andExpect(status().isOk())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString());
assertThat(response.read("$.value.password").toString(), is(not(equalTo(password))));
}
@Override
protected Bean _createBean( Class returnType, String inputData ) throws Exception
{
System.out.println( inputData );
DocumentContext ctx = JsonPath.parse( inputData );
return populateBean( ctx, returnType, "" );
}