Java Code Examples for com.jayway.jsonpath.JsonPath#read()

The following examples show how to use com.jayway.jsonpath.JsonPath#read() . 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 vote down vote up
@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: StepTest.java    From zerocode with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldDeserializeSingleStep() throws Exception {
    String jsonDocumentAsString = smartUtils.getJsonDocumentAsString("unit_test_files/engine_unit_test_jsons/01_test_json_single_step.json");
    Step stepDeserialized = mapper.readValue(jsonDocumentAsString, Step.class);
    assertThat(stepDeserialized, notNullValue());
    final String requestJsonAsString = stepDeserialized.getRequest().toString();
    assertThat(requestJsonAsString, containsString("firstName"));

    Object queryParams = JsonPath.read(requestJsonAsString, "$.queryParams");
    Object requestHeaders = JsonPath.read(requestJsonAsString, "$.headers");

    assertThat(queryParams.toString(), is("{param1=value1, invId=10101}"));
    assertThat(requestHeaders.toString(), is("{Content-Type=application/json;charset=UTF-8, Cookie=cookie_123}"));

    Map<String, Object> headerMap = (HashMap) requestHeaders;
    Map<String, Object> queryParamsMap = (HashMap) queryParams;

    assertThat(headerMap.get("Cookie"), is("cookie_123"));
    assertThat(queryParamsMap.get("invId"), is(10101));
    assertThat(stepDeserialized.getAssertions().get("status").asInt(), is(201));
    assertThat(stepDeserialized.getAssertions().get("status").asLong(), is(201L));
    assertThat(stepDeserialized.getAssertions().get("status").asText(), is("201"));
}
 
Example 3
Source File: DingDingAccessTokenUtil.java    From flink-learning with Apache License 2.0 7 votes vote down vote up
/**
 * 根据微应用 key 和 secret 获取 access_token
 *
 * @param appKey
 * @param appSecret
 * @return
 */
public static String getAccessToken(String appKey, String appSecret) {
    String accessToken = "";
    String dingDingAccessTocken = expireCache.getIfPresent(DING_DING_ACCESS_TOKEN);
    if (dingDingAccessTocken == null || "".equals(dingDingAccessTocken)) {
        String result = "";
        try {
            result = HttpUtil.doGet(DING_DING_GET_TOKEN_URL + "?appkey=" + appKey + "&appsecret=" + appSecret);
            accessToken = JsonPath.read(result, "$.access_token");
            if (accessToken != null && !"".equals(accessToken)) {
                expireCache.put(DING_DING_ACCESS_TOKEN, String.valueOf(accessToken));
                log.info("get ding ding access token = {}", String.valueOf(accessToken));
            }
        } catch (Exception e) {
            log.error("--------------httpclient do get request exception , msg = {}, result = {}",
                    Throwables.getStackTraceAsString(e), result);
        }
    } else {
        accessToken = dingDingAccessTocken;
    }
    return accessToken;
}
 
Example 4
Source File: DingDingAccessTokenUtil.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
/**
 * 根据微应用 key 和 secret 获取 access_token
 *
 * @param appKey
 * @param appSecret
 * @return
 */
public static String getAccessToken(String appKey, String appSecret) {
    String accessToken = "";
    String dingDingAccessTocken = expireCache.getIfPresent(DING_DING_ACCESS_TOKEN);
    if (dingDingAccessTocken == null || "".equals(dingDingAccessTocken)) {
        String result = "";
        try {
            result = HttpUtil.doGet(DING_DING_GET_TOKEN_URL + "?appkey=" + appKey + "&appsecret=" + appSecret);
            accessToken = JsonPath.read(result, "$.access_token");
            if (accessToken != null && !"".equals(accessToken)) {
                expireCache.put(DING_DING_ACCESS_TOKEN, String.valueOf(accessToken));
                log.info("get ding ding access token = {}", String.valueOf(accessToken));
            }
        } catch (Exception e) {
            log.error("--------------httpclient do get request exception , msg = {}, result = {}",
                    Throwables.getStackTraceAsString(e), result);
        }
    } else {
        accessToken = dingDingAccessTocken;
    }
    return accessToken;
}
 
Example 5
Source File: HttpUtils.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: StashFacade.java    From sputnik with Apache License 2.0 6 votes vote down vote up
SingleFileChanges changesForSingleFile(String filename) {
    try {
        String response = stashConnector.getDiffByLine(filename);
        JSONArray diffJsonList = JsonPath.read(response, "$.diffs[*].hunks[*].segments[*]");
        JSONArray lineCommentJsonList = JsonPath.read(response, "$.diffs[*].lineComments[*]['text', 'id']");
        List<DiffSegment> segments = transform(diffJsonList, DiffSegment.class);
        List<LineComment> lineComments = transform(lineCommentJsonList, LineComment.class);
        SingleFileChanges changes = SingleFileChanges.builder().filename(filename).build();
        for (DiffSegment segment : segments) {
            for (LineSegment line : segment.lines) {
                changes.addChange(line.destination, ChangeType.valueOf(segment.type), getComment(lineComments, line.commentIds));
            }
        }
        return changes;
    } catch (URISyntaxException | IOException e) {
        throw new StashException("Error parsing json strings to objects", e);
    }
}
 
Example 7
Source File: ServiceRequestsComparatorHelper.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
private String getVariableFromServiceRequest(String request, ScenarioVariableFromServiceRequest variable) {
    switch (variable.getMatchingType()) {
        case REGEXP:
            return RegexUtils.getValueByRegex(request, variable.getExpression());
        case XPATH:
            try {
                return XMLUtils.getValueByXPath(request, variable.getExpression());
            } catch (Exception e) {
                log.error("Unable to read value from XML by XPath", e);
                return EMPTY;
            }
        case JSONPATH:
            // Same as default
        default:
            return JsonPath.read(request, variable.getExpression());
    }
}
 
Example 8
Source File: ZhihuHotProcessor.java    From hot-crawler with MIT License 6 votes vote down vote up
@Override
public List<Info> getInfoDataByJson(String json) {
    List<Info> list = new ArrayList<>();
    if (json == null)
    {
        return list;
    }

    List<String> titles = JsonPath.read(json, "$.data.[*].target.title");
    List<String> urls = JsonPath.read(json, "$.data.[*].target.url");

    for (int i = 0; i < urls.size(); i++)
    {
        urls.set(i, urls.get(i).replace("https://api.zhihu.com/questions", this.prefix + "/question"));
    }

    for (int i = 1; i < titles.size(); i++)
    {
        list.add(new Info(String.valueOf(i), titles.get(i), urls.get(i)));
    }
    return list;
}
 
Example 9
Source File: ResourceVersioningControllerIntegrationTest.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String createAndDeleteResource(UserDetails user, String resourceTypeCode, String type, Map<String, String> params) throws Exception {
    String mimeType = type.equals("image") ? "application/jpeg" : "application/pdf";
    ResultActions result = performCreateResource(user, type, "free", mimeType);
    String bodyResult = result.andReturn().getResponse().getContentAsString();
    String resourceId = JsonPath.read(bodyResult, "$.payload.id");

    performDeleteResource(user, resourceTypeCode, resourceId)
            .andExpect(status().isOk());

    result = listTrashedResources(user, params)
            .andExpect(status().isOk());
    bodyResult = result.andReturn().getResponse().getContentAsString();

    Integer payloadSize = JsonPath.read(bodyResult, "$.payload.size()");
    for (int i = 0; i < payloadSize; i++) {
        if (JsonPath.read(bodyResult, "$.payload[" + i + "].description").equals("image_test.jpeg")
                || JsonPath.read(bodyResult, "$.payload[" + i + "].description").equals("file_test.jpeg")) {
            return JsonPath.read(bodyResult, "$.payload[" + i + "].id");
        }
    }
    return null;
}
 
Example 10
Source File: VersioningConfigurationControllerIntegrationTest.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testPutVersioningConfiguration() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    try {
        String accessToken = mockOAuthInterceptor(user);
        final String versioningConfigurationResult = updateVersioningConfiguration("json/1_PUT_versioning_configuration.json", accessToken);
        List<String> contentsToIgnore = JsonPath.read(versioningConfigurationResult, "$.contentsToIgnore");
        List<String> contentTypesToIgnore = JsonPath.read(versioningConfigurationResult, "$.contentTypesToIgnore");
        boolean deleteMidVersions = JsonPath.read(versioningConfigurationResult, "$.deleteMidVersions");
        assertThat(contentsToIgnore.get(0)).isEqualTo("TST1");
        assertThat(contentTypesToIgnore.get(0)).isEqualTo("CT1");
        assertThat(deleteMidVersions).isEqualTo(true);
    } finally {
        setDefaultVersioningConfiguration();
    }
}
 
Example 11
Source File: MarcElasticsearchClient.java    From metadata-qa-marc with GNU General Public License v3.0 5 votes vote down vote up
public int getNumberOfTweets() throws IOException {
  Map<String, String> params = new HashMap<>();
  params.put("q", "*:*");
  params.put("size", "0");
  Response response = restClient.performRequest(
        "GET",
        "/twitter/tweet/_search",
        params
  );
  Object jsonObject = jsonProvider.parse(EntityUtils.toString(response.getEntity()));
  int hits = JsonPath.read(jsonObject, "$.hits.total");
  return hits;
}
 
Example 12
Source File: JsonFunctions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public T apply(JsonElement input) {
    if (input == null) return null;
    String jsonString = input.toString();
    Object rawElement = JsonPath.read(jsonString, path);
    return (T) rawElement;
}
 
Example 13
Source File: ProducerRawRecordsTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void test_ProducerRecordsNull() {
    final String json = "{\n" +
            "\"recordType\": \"RAW\"," +
            "\"file\": \"abc.txt\"," +
            "\"async\": true" +
            "}";

    Object recordType = JsonPath.read(json, "$.recordType");
    assertThat(recordType.toString(), is("RAW"));

    ProducerRawRecords rawRecords = gson.fromJson(json, ProducerRawRecords.class);
    assertThat(rawRecords.getFile(), is("abc.txt"));
    assertThat(rawRecords.getRecords().size(), is(0));
    assertThat(rawRecords.getAsync(), is(true));

    ProducerRecord record = new ProducerRecord("topic1", 1, 2);

    boolean added = rawRecords.getRecords().add(record);
    assertThat(added, is(true));
    assertThat(rawRecords.getRecords().size(), is(0));
    rawRecords.setRecords(Arrays.asList(record));
    assertThat(rawRecords.getRecords().size(), is(1));


    ProducerRawRecords rawRecords2 = new ProducerRawRecords(null, true, "RAW", "abc.txt");
    assertThat(rawRecords2.getRecords().size(), is(0));
    rawRecords2.getRecords().add(record);
    assertThat(rawRecords2.getRecords().size(), is(1));
}
 
Example 14
Source File: JSONPathProcessor.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Statement> execute_node_fromdependency(SesameDataSet dataset, String expression,TriplesMap map,
		 RMLPerformer performer, Object node
		){
	this.map = map;
	Object val = JsonPath.read(node, expression);

	return execute(dataset,map, performer, val);
}
 
Example 15
Source File: GetTaskDetails.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
@Action(name = GET_TASK_DETAILS_OPERATION_NAME,
        description = GET_TASK_DETAILS_OPERATION_DESC,
        outputs = {
                @Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC),
                @Output(value = EXCEPTION, description = EXCEPTION_DESC),
                @Output(value = STATUS_CODE, description = STATUS_CODE_DESC),
                @Output(value = VM_UUID, description = VM_UUID_DESC),
                @Output(value = TASK_STATUS, description = TASK_STATUS_DESC)
        },
        responses = {
                @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL,
                        responseType = RESOLVED, description = SUCCESS_DESC),
                @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL,
                        responseType = ERROR, description = FAILURE_DESC)})
public Map<String, String> execute(@Param(value = HOSTNAME, required = true, description = HOSTNAME_DESC) String hostname,
                                   @Param(value = PORT, description = PORT_DESC) String port,
                                   @Param(value = USERNAME, required = true, description = USERNAME_DESC) String username,
                                   @Param(value = PASSWORD, encrypted = true, required = true, description = PASSWORD_DESC) String password,
                                   @Param(value = TASK_UUID, required = true, description = TASK_UUID_DESC) String taskUUID,
                                   @Param(value = INCLUDE_SUBTASKS_INFO, description = INCLUDE_SUBTASKS_INFO_DESC) String includeSubtasksInfo,
                                   @Param(value = API_VERSION, description = API_VERSION_DESC) String apiVersion,
                                   @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost,
                                   @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort,
                                   @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername,
                                   @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword,
                                   @Param(value = TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots,
                                   @Param(value = X509_HOSTNAME_VERIFIER, description = X509_DESC) String x509HostnameVerifier,
                                   @Param(value = TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore,
                                   @Param(value = TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword,
                                   @Param(value = CONNECT_TIMEOUT, description = CONNECT_TIMEOUT_DESC) String connectTimeout,
                                   @Param(value = SOCKET_TIMEOUT, description = SOCKET_TIMEOUT_DESC) String socketTimeout,
                                   @Param(value = KEEP_ALIVE, description = KEEP_ALIVE_DESC) String keepAlive,
                                   @Param(value = CONNECTIONS_MAX_PER_ROUTE, description = CONN_MAX_ROUTE_DESC) String connectionsMaxPerRoute,
                                   @Param(value = CONNECTIONS_MAX_TOTAL, description = CONN_MAX_TOTAL_DESC) String connectionsMaxTotal) {
    port = defaultIfEmpty(port, DEFAULT_NUTANIX_PORT);
    apiVersion = defaultIfEmpty(apiVersion, DEFAULT_API_VERSION);
    proxyHost = defaultIfEmpty(proxyHost, EMPTY);
    proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
    proxyUsername = defaultIfEmpty(proxyUsername, EMPTY);
    proxyPassword = defaultIfEmpty(proxyPassword, EMPTY);
    trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE);
    includeSubtasksInfo = defaultIfEmpty(includeSubtasksInfo, BOOLEAN_FALSE);
    x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT);
    trustKeystore = defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE);
    trustPassword = defaultIfEmpty(trustPassword, CHANGEIT);
    connectTimeout = defaultIfEmpty(connectTimeout, CONNECT_TIMEOUT_CONST);
    socketTimeout = defaultIfEmpty(socketTimeout, ZERO);
    keepAlive = defaultIfEmpty(keepAlive, BOOLEAN_TRUE);
    connectionsMaxPerRoute = defaultIfEmpty(connectionsMaxPerRoute, CONNECTIONS_MAX_PER_ROUTE_CONST);
    connectionsMaxTotal = defaultIfEmpty(connectionsMaxTotal, CONNECTIONS_MAX_TOTAL_CONST);
    final List<String> exceptionMessage = verifyCommonInputs(proxyPort, trustAllRoots,
            connectTimeout, socketTimeout, keepAlive, connectionsMaxPerRoute, connectionsMaxTotal);
    if (!exceptionMessage.isEmpty()) {
        return getFailureResultsMap(StringUtilities.join(exceptionMessage, NEW_LINE));
    }

    try {
        final Map<String, String> result = getTaskDetails(NutanixGetTaskDetailsInputs.builder()
                .taskUUID(taskUUID)
                .includeSubtasksInfo(includeSubtasksInfo)
                .commonInputs(NutanixCommonInputs.builder()
                        .hostname(hostname)
                        .port(port)
                        .username(username)
                        .password(password)
                        .apiVersion(apiVersion)
                        .proxyHost(proxyHost)
                        .proxyPort(proxyPort)
                        .proxyUsername(proxyUsername)
                        .proxyPassword(proxyPassword)
                        .trustAllRoots(trustAllRoots)
                        .x509HostnameVerifier(x509HostnameVerifier)
                        .trustKeystore(trustKeystore)
                        .trustPassword(trustPassword)
                        .connectTimeout(connectTimeout)
                        .socketTimeout(socketTimeout)
                        .keepAlive(keepAlive)
                        .connectionsMaxPerRoot(connectionsMaxPerRoute)
                        .connectionsMaxTotal(connectionsMaxTotal)
                        .build()).build());

        final String returnMessage = result.get(RETURN_RESULT);
        final Map<String, String> results = getOperationResults(result, returnMessage, returnMessage, returnMessage);
        final int statusCode = Integer.parseInt(result.get(STATUS_CODE));

        String taskStatus = JsonPath.read(returnMessage, TASK_STATUS_PATH);
        if (statusCode >= 200 && statusCode < 300) {
            results.put(TASK_STATUS, taskStatus);
        } else {
            return getTaskFailureResults(hostname, statusCode, taskStatus, returnMessage, returnMessage);
        }
        return results;
    } catch (Exception exception) {
        return getFailureResultsMap(exception);
    }
}
 
Example 16
Source File: ResourcesControllerIntegrationTest.java    From entando-components with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testCreateEditWithoutFileDeleteFileResource() throws Exception {
    UserDetails user = createAccessToken();
    String createdId = null;

    try {
        ResultActions result = performCreateResource(user, "file", "free", Arrays.stream(new String[]{"resCat1", "resCat2"}).collect(Collectors.toList()), "application/pdf")
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.payload.id", Matchers.anything()))
            .andExpect(jsonPath("$.payload.categories.size()", is(2)))
            .andExpect(jsonPath("$.payload.categories[0]", is("resCat1")))
            .andExpect(jsonPath("$.payload.categories[1]", is("resCat2")))
            .andExpect(jsonPath("$.payload.group", is("free")))
            .andExpect(jsonPath("$.payload.description", is("file_test.jpeg")))
            .andExpect(jsonPath("$.payload.size", is("2 Kb")))
            .andExpect(jsonPath("$.payload.path", startsWith("/Entando/resources/cms/documents/file_test")));

        createdId = JsonPath.read(result.andReturn().getResponse().getContentAsString(), "$.payload.id");

        performGetResources(user, "file", null)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.payload.size()", is(4)));

        List<String> categories = Arrays.stream(new String[]{"resCat1"}).collect(Collectors.toList());

        performEditResource(user, "file", createdId, "new file description", categories, false)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.payload.id", is(createdId)))
            .andExpect(jsonPath("$.payload.categories.size()", is(1)))
            .andExpect(jsonPath("$.payload.categories[0]", is("resCat1")))
            .andExpect(jsonPath("$.payload.group", is("free")))
            .andExpect(jsonPath("$.payload.description", is("new file description")))
            .andExpect(jsonPath("$.payload.size", is("2 Kb")));
            //.andExpect(jsonPath("$.payload.path", startsWith("/Entando/resources/cms/documents/file_test")));
    } finally {
        if (createdId != null) {
            performDeleteResource(user, "file", createdId)
                .andDo(print())
                .andExpect(status().isOk());

            performGetResources(user, "file", null)
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.payload.size()", is(3)));
        }
    }
}
 
Example 17
Source File: ItemResourceOSGiTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private List<String> readItemNamesFromResponse(Response response) throws IOException {
    String jsonResponse = IOUtils.toString((InputStream) response.getEntity());
    return JsonPath.read(jsonResponse, "$..name");
}
 
Example 18
Source File: ActivityStreamControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testOrderLogRecord() throws Exception {
    String pageCode1 = "draft_page_100";
    String pageCode2 = "draft_page_200";
    try {
        UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
        String accessToken = mockOAuthInterceptor(user);
        Integer startSize = this.extractCurrentSize(accessToken);
        this.initTestObjects(accessToken, pageCode1, pageCode2);

        //assert record is present
        Integer actualSize = this.extractCurrentSize(accessToken);
        Assert.assertEquals(2, (actualSize - startSize));
        ResultActions result = mockMvc
                .perform(get("/activityStream")
                        .header("Authorization", "Bearer " + accessToken));
        result.andExpect(status().isOk());
        String bodyResult = result.andReturn().getResponse().getContentAsString();
        Integer firstId = JsonPath.read(bodyResult, "$.payload[0].id");
        Integer secondId = JsonPath.read(bodyResult, "$.payload[1].id");

        result = mockMvc
                .perform(get("/activityStream")
                        .param("direction", "DESC")
                        .header("Authorization", "Bearer " + accessToken));
        result.andExpect(status().isOk());
        result.andExpect(jsonPath("$.payload", Matchers.hasSize(actualSize)));
        result.andExpect(jsonPath("$.metaData.pageSize", is(100)));
        result.andExpect(jsonPath("$.metaData.lastPage", is(1)));
        result.andExpect(jsonPath("$.metaData.totalItems", is(actualSize)));
        bodyResult = result.andReturn().getResponse().getContentAsString();
        Integer firstIdInNewPos = JsonPath.read(bodyResult, "$.payload[" + (actualSize - 1) + "].id");
        Integer secondIdInNewPos = JsonPath.read(bodyResult, "$.payload[" + (actualSize - 2) + "].id");

        Assert.assertEquals(firstId, firstIdInNewPos);
        Assert.assertEquals(secondId, secondIdInNewPos);

        result = mockMvc
                .perform(get("/activityStream")
                        .param("pageSize", "1").param("direction", "DESC")
                        .header("Authorization", "Bearer " + accessToken));
        result.andExpect(status().isOk());
        result.andExpect(jsonPath("$.payload", Matchers.hasSize(1)));
        result.andExpect(jsonPath("$.metaData.pageSize", is(1)));
        result.andExpect(jsonPath("$.metaData.lastPage", is(actualSize)));
        result.andExpect(jsonPath("$.metaData.totalItems", is(actualSize)));

    } finally {
        this.destroyLogs(pageCode1, pageCode2);
    }
}
 
Example 19
Source File: UnapprovedServicesAndRolePlugin.java    From fullstop with Apache License 2.0 3 votes vote down vote up
private String getRoleName(final CloudTrailEvent event) {

        if (event.getEventData() != null
                && event.getEventData().getRequestParameters() != null
                && !event.getEventData().getRequestParameters().isEmpty()) {

            return JsonPath.read(event.getEventData().getRequestParameters(), "$.roleName");

        } else {
            return null;
        }

    }
 
Example 20
Source File: JsonPathExample.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
/**
 * Get all issues ids
 */
@Test
public void all_issues_ids () {
	
	List<String> issueIds = JsonPath.read(githubIssues, "$.[*].id");

	logger.info(issueIds);
	
	assertEquals(8, issueIds.size());
}