com.jayway.jsonpath.DocumentContext Java Examples

The following examples show how to use com.jayway.jsonpath.DocumentContext. 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: TypeTest.java    From JsonTemplate with Apache License 2.0 6 votes vote down vote up
@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))));
}
 
Example #2
Source File: DashboardClientTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #3
Source File: TypeTest.java    From JsonTemplate with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #4
Source File: ICSAttachmentWorkflowTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: ICSAttachmentWorkflowTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: Script.java    From karate with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #7
Source File: JSONIO.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
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 );
    }
}
 
Example #8
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 6 votes vote down vote up
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));
    }
}
 
Example #9
Source File: JsonPathIntegrationCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: ServiceIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@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);
}
 
Example #11
Source File: SetMailboxesMethodStepdefs.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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;
    });
}
 
Example #12
Source File: VariableTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(TestUtils.REPEATED_COUNT)
void test_arrayInSingleParam() {
    String[] value = new String[]{"A", "B", "C", "D"};
    JsonTemplate jsonTemplate = new JsonTemplate("{aField: @s($myValue)}").withVar("myValue", value);
    DocumentContext document = parse(jsonTemplate);
    assertThat(document.read("$.aField", String.class), isIn(value));
}
 
Example #13
Source File: ScriptTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testMatchJsonPathThatReturnsList() {
    DocumentContext doc = JsonPath.parse("{ foo: [{ bar: 1}, {bar: 2}, {bar: 3}]}");
    ScenarioContext ctx = getContext();
    ctx.vars.put("json", doc);
    Script.assign("list", "json.foo", ctx);
    ScriptValue list = ctx.vars.get("list");
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, list, "$[0]", "{ bar: 1}", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, list, "$[0].bar", "1", ctx).pass);
}
 
Example #14
Source File: GenerateModeTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void generatingACredential_inNoOverwriteMode_doesNotUpdateTheCredential() throws Exception {
    MockHttpServletRequestBuilder postRequest = post("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{" +
                    "\"type\":\"password\"," +
                    "\"name\":\"" + CREDENTIAL_NAME + "\"" +
                    "}");

    DocumentContext response = JsonPath.parse(mockMvc.perform(postRequest).andExpect(status().isOk())
            .andDo(print())
            .andReturn()
            .getResponse()
            .getContentAsString());

    final String versionId = response.read("$.id").toString();

    postRequest = post("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{" +
                    "\"type\":\"password\"," +
                    "\"name\":\"" + CREDENTIAL_NAME + "\"," +
                    "\"mode\": \"no-overwrite\"" +
                    "}");

    response = JsonPath.parse(mockMvc.perform(postRequest).andExpect(status().isOk())
            .andDo(print())
            .andReturn()
            .getResponse()
            .getContentAsString());

    assertThat(response.read("$.id").toString(), is(equalTo(versionId)));
}
 
Example #15
Source File: VariableTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
void test_integerAsSingleParamInStringType() {
    int value = 2;
    JsonTemplate jsonTemplate = new JsonTemplate("{aField: @s($myValue)}").withVar("myValue", value);
    DocumentContext document = parse(jsonTemplate);
    assertThat(document.read("$.aField", String.class), is(Integer.toString(value)));
}
 
Example #16
Source File: VariableTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
void test_stringAsSingleParamInStringType() {
    String value = "helloworld";
    JsonTemplate jsonTemplate = new JsonTemplate("{aField: @s($myValue)}").withVar("myValue", value);
    DocumentContext document = parse(jsonTemplate);
    assertThat(document.read("$.aField", String.class), is(value));
}
 
Example #17
Source File: TypeTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
void test_typeWithMapParam() {
    DocumentContext document = parse(new JsonTemplate(
            "@address:{city:@s(length=10),street:@s(length=20),number:@i(min=1000)}," +
                    "{office:@address, home:@address}"));
    assertThat(document.read("$.office.city", String.class).length(), is(10));
    assertThat(document.read("$.office.street", String.class).length(), is(20));
    assertThat(document.read("$.office.number", Integer.class), greaterThanOrEqualTo(1000));
    assertThat(document.read("$.home.city", String.class).length(), is(10));
    assertThat(document.read("$.home.street", String.class).length(), is(20));
    assertThat(document.read("$.home.number", Integer.class), greaterThanOrEqualTo(1000));
}
 
Example #18
Source File: VariableTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
void test_listVariable() {
    JsonTemplate jsonTemplate = new JsonTemplate("{letters : $letters}")
            .withVar("letters", Arrays.asList("A", "B", "C"));
    DocumentContext document = parse(jsonTemplate);
    assertThat(document.read("$.letters[0]", String.class), is("A"));
    assertThat(document.read("$.letters[1]", String.class), is("B"));
    assertThat(document.read("$.letters[2]", String.class), is("C"));
}
 
Example #19
Source File: JsonUtilsTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testJsonArrayAsRoot() {
    String raw = "[1, 2, 3]";
    DocumentContext doc = JsonUtils.toJsonDoc(raw);
    Object sec = doc.read("$[1]");
    assertEquals(2, sec);
}
 
Example #20
Source File: UserGenerationTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@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))));
}
 
Example #21
Source File: ApiCatalogEndpointIntegrationTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void whenCatalogApiDoc_thenResponseOK() throws Exception {
    final HttpResponse response = getResponse(GET_API_CATALOG_API_DOC_ENDPOINT, HttpStatus.SC_OK);

    // When
    final String jsonResponse = EntityUtils.toString(response.getEntity());

    String apiCatalogSwagger = "\n**************************\n" +
        "Integration Test: API Catalog Swagger" +
        "\n**************************\n" +
        jsonResponse +
        "\n**************************\n";
    DocumentContext jsonContext = JsonPath.parse(jsonResponse);

    String swaggerHost = jsonContext.read("$.host");
    String swaggerBasePath = jsonContext.read("$.basePath");
    LinkedHashMap paths = jsonContext.read("$.paths");
    LinkedHashMap definitions = jsonContext.read("$.definitions");

    // Then
    assertFalse(apiCatalogSwagger, paths.isEmpty());
    assertFalse(apiCatalogSwagger, definitions.isEmpty());
    assertEquals(apiCatalogSwagger, baseHost, swaggerHost);
    assertEquals(apiCatalogSwagger, "/api/v1/apicatalog", swaggerBasePath);
    assertNull(apiCatalogSwagger, paths.get("/status/updates"));
    assertNotNull(apiCatalogSwagger, paths.get("/containers/{id}"));
    assertNotNull(apiCatalogSwagger, paths.get("/containers"));
    assertNotNull(apiCatalogSwagger, paths.get("/apidoc/{serviceId}/{apiVersion}"));
    assertNotNull(apiCatalogSwagger, definitions.get("APIContainer"));
    assertNotNull(apiCatalogSwagger, definitions.get("APIService"));
    assertNotNull(apiCatalogSwagger, definitions.get("TimeZone"));
}
 
Example #22
Source File: JsonUtilsTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testYamlToMutation() throws Exception {
    InputStream is = getClass().getResourceAsStream("mutation.yaml");
    String yaml = FileUtils.toString(is);
    DocumentContext doc = JsonUtils.fromYaml(yaml);
    assertTrue(doc.jsonString().contains("[\"id\",\"name\",\"notes\",\"deleted\"]"));
}
 
Example #23
Source File: JSONIOTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Test
public void readFile ()
                throws ManipulationException, IOException
{
    DocumentContext o = jsonIO.parseJSON( npmFile );
    logger.debug ("Read {} ", o.jsonString());
    logger.debug ("File {}", FileUtils.readFileToString( npmFile, jsonIO.getCharset() ) );
    // They won't be equal as jsonString is not pretty printed.
    assertNotEquals( o.jsonString(), FileUtils.readFileToString( npmFile, jsonIO.getCharset() ) );
    assertNotNull( o );
}
 
Example #24
Source File: JSONIOTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Test
public void testCharsetUTF32BE() throws ManipulationException, IOException {
    URL resource = this.getClass().getResource( "npm-shrinkwrap-utf32be.json" );
    File npmFile = new File( resource.getFile() );
    DocumentContext doc = jsonIO.parseJSON( npmFile );
    assertEquals( Charset.forName( "UTF-32BE" ), jsonIO.getCharset() );
    File target = tf.newFile();
    jsonIO.writeJSON( target, doc );
    assertEquals( JsonEncoding.UTF32_BE, JSONIO.detectEncoding( target ) );
    assertTrue( FileUtils.contentEqualsIgnoreEOL( npmFile, target, jsonIO.getCharset().name() ) );
}
 
Example #25
Source File: CreateServiceInstanceResponseTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
void responseWithDefaultsIsBuilt() {
	CreateServiceInstanceResponse response = CreateServiceInstanceResponse.builder()
			.build();

	assertThat(response.isAsync()).isEqualTo(false);
	assertThat(response.getOperation()).isNull();
	assertThat(response.isInstanceExisted()).isEqualTo(false);
	assertThat(response.getDashboardUrl()).isNull();

	DocumentContext json = JsonUtils.toJsonPath(response);

	assertThat(json).hasNoPath("$.operation");
	assertThat(json).hasNoPath("$.dashboard_url");
}
 
Example #26
Source File: DefaultTypeTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
void test_customArrayTypeAsDefaultType() {
    DocumentContext document = parse(new JsonTemplate("@names:@s[](3), @names{group1, group2}"));
    assertThat(document.read("$.group1[0]", String.class), is(notNullValue()));
    assertThat(document.read("$.group1[1]", String.class), is(notNullValue()));
    assertThat(document.read("$.group1[2]", String.class), is(notNullValue()));
    assertThat(document.read("$.group2[0]", String.class), is(notNullValue()));
    assertThat(document.read("$.group2[1]", String.class), is(notNullValue()));
    assertThat(document.read("$.group2[2]", String.class), is(notNullValue()));
}
 
Example #27
Source File: UserGenerationTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void whenGivenAUsernameAndPasswordParameters_usesUsernameAndGeneratesPassword() throws Exception {
  final MockHttpServletRequestBuilder post = post("/api/v1/data")
    .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
    .accept(APPLICATION_JSON)
    .contentType(APPLICATION_JSON)
    .content("{" +
      "\"name\": \"" + credentialName1 + "\"," +
      "\"type\": \"user\"," +
      "\"value\": {" +
      "\"username\": \"test-username\"" +
      "}," +
      "\"parameters\": {" +
      "\"length\": 40," +
      "\"exclude_upper\": true," +
      "\"exclude_lower\": true," +
      "\"exclude_number\": false," +
      "\"include_special\": false" +
      "}" +
      "}"
    );

  final MockHttpServletResponse response = this.mockMvc.perform(post).andExpect(status()
    .isOk()).andReturn().getResponse();

  final DocumentContext parsedResponse = JsonPath.parse(response.getContentAsString());

  final String password = parsedResponse.read("$.value.password");
  assertThat(password.length(), equalTo(40));
  assertThat(isDigits(password), equalTo(true));

  final String username = parsedResponse.read("$.value.username");
  assertThat(username, equalTo("test-username"));
}
 
Example #28
Source File: JSONBeanFactory.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Bean _createBean( Class returnType, String inputData ) throws Exception
{
    System.out.println( inputData );
    DocumentContext ctx = JsonPath.parse( inputData );
    
    return populateBean( ctx, returnType, "" );
}
 
Example #29
Source File: JsonUtilsTest.java    From karate with MIT License 5 votes vote down vote up
@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);
}
 
Example #30
Source File: ApiMediationLayerStartupChecker.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
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());
}