Search in sources :

Example 61 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project goci by EBISPOT.

the class EnsemblController method getAncestors.

public Map<String, String> getAncestors(String efoTerm) throws IOException {
    Map<String, String> result = new HashMap<>();
    String uri = olsServer.concat(olsEfoTerms);
    if (efoTerm.contains("http")) {
        uri = uri.concat("?").concat(efoTerm);
    } else {
        uri = uri.concat(olsShortForm).concat(efoTerm);
    }
    RestTemplate restTemplate = new RestTemplate();
    String efoObject = null;
    try {
        efoObject = restTemplate.getForObject(uri, String.class);
    } catch (HttpClientErrorException ex) {
        result.put("error", "Term ".concat(efoTerm).concat(" not found in EFO"));
    }
    if (efoObject != null) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(efoObject);
        JsonNode responseNode = node.get("_embedded").get("terms").get(0);
        String ancestors_link = responseNode.get("_links").get("hierarchicalAncestors").get("href").asText().trim();
        ancestors_link = java.net.URLDecoder.decode(ancestors_link, "UTF-8");
        String label = responseNode.get("label").asText().trim();
        String iri = responseNode.get("iri").asText().trim();
        String ancestorsObject = restTemplate.getForObject(ancestors_link, String.class);
        result.put("iri", iri);
        result.put("label", label);
        result.put("ancestors", ancestorsObject);
    }
    return result;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashMap(java.util.HashMap) RestTemplate(org.springframework.web.client.RestTemplate) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 62 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project geode by apache.

the class QueryResultData method executeQueryTestCases.

private void executeQueryTestCases() {
    HttpHeaders headers = setAcceptAndContentTypeHeaders();
    HttpEntity<Object> entity;
    int totalRequests = TEST_DATA.length;
    String expectedEx = null;
    for (int index = 0; index < totalRequests; index++) {
        try {
            expectedEx = addExpectedException(index);
            final String restRequestUrl = createRestURL(this.baseURL, TEST_DATA[index][URL_INDEX]);
            entity = new HttpEntity<>(TEST_DATA[index][REQUEST_BODY_INDEX], headers);
            ResponseEntity<String> result = RestTestUtils.getRestTemplate().exchange(restRequestUrl, (HttpMethod) TEST_DATA[index][METHOD_INDEX], entity, String.class);
            validateGetAllResult(index, result);
            validateQueryResult(index, result);
            assertEquals(result.getStatusCode(), TEST_DATA[index][STATUS_CODE_INDEX]);
            assertEquals(result.hasBody(), ((Boolean) TEST_DATA[index][RESPONSE_HAS_BODY_INDEX]).booleanValue());
            verifyRegionSize(index, result);
        // TODO:
        // verify location header
        } catch (HttpClientErrorException e) {
            if (VALID_409_URL_INDEXS.contains(index)) {
                // create-409, conflict testcase. [create on already existing key]
                assertEquals(e.getStatusCode(), TEST_DATA[index][STATUS_CODE_INDEX]);
                assertEquals(StringUtils.hasText(e.getResponseBodyAsString()), ((Boolean) TEST_DATA[index][RESPONSE_HAS_BODY_INDEX]).booleanValue());
            } else if (VALID_400_URL_INDEXS.contains(index)) {
                // 400, Bad Request testcases. [create with malformed Json]
                assertEquals(e.getStatusCode(), TEST_DATA[index][STATUS_CODE_INDEX]);
                assertEquals(StringUtils.hasText(e.getResponseBodyAsString()), ((Boolean) TEST_DATA[index][RESPONSE_HAS_BODY_INDEX]).booleanValue());
            } else if (VALID_404_URL_INDEXS.contains(index)) {
                // create-404, Not Found testcase. [create on not-existing region]
                assertEquals(e.getStatusCode(), TEST_DATA[index][STATUS_CODE_INDEX]);
                assertEquals(StringUtils.hasText(e.getResponseBodyAsString()), ((Boolean) TEST_DATA[index][RESPONSE_HAS_BODY_INDEX]).booleanValue());
            } else if (VALID_405_URL_INDEXS.contains(index)) {
                // create-404, Not Found testcase. [create on not-existing region]
                assertEquals(e.getStatusCode(), TEST_DATA[index][STATUS_CODE_INDEX]);
                assertEquals(StringUtils.hasText(e.getResponseBodyAsString()), ((Boolean) TEST_DATA[index][RESPONSE_HAS_BODY_INDEX]).booleanValue());
            } else {
                fail("Index:" + index + " " + TEST_DATA[index][METHOD_INDEX] + " " + TEST_DATA[index][URL_INDEX] + " should not have thrown exception ");
            }
        } catch (HttpServerErrorException se) {
            // index=4, create- 500, INTERNAL_SERVER_ERROR testcase. [create on Region with
            // DataPolicy=Empty set]
            // index=7, create- 500, INTERNAL_SERVER_ERROR testcase. [Get, attached cache loader throws
            // Timeout exception]
            // index=11, put- 500, [While doing R.put, CacheWriter.beforeCreate() has thrown
            // CacheWriterException]
            // .... and more test cases
            assertEquals(TEST_DATA[index][STATUS_CODE_INDEX], se.getStatusCode());
            assertEquals(TEST_DATA[index][RESPONSE_HAS_BODY_INDEX], StringUtils.hasText(se.getResponseBodyAsString()));
        } catch (Exception e) {
            caught("caught Exception in executeQueryTestCases " + "Index:" + index + " " + TEST_DATA[index][METHOD_INDEX] + " " + TEST_DATA[index][URL_INDEX] + " :: Unexpected ERROR...!!", e);
        } finally {
            c.getLogger().info("<ExpectedException action=remove>" + expectedEx + "</ExpectedException>");
        }
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) JSONObject(org.json.JSONObject) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) TimeoutException(org.apache.geode.cache.TimeoutException) JSONException(org.json.JSONException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) CacheWriterException(org.apache.geode.cache.CacheWriterException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) UnknownHostException(java.net.UnknownHostException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException)

Example 63 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project dhis2-core by dhis2.

the class DefaultSynchronizationManager method isRemoteServerAvailable.

// -------------------------------------------------------------------------
// SynchronizatonManager implementation
// -------------------------------------------------------------------------
@Override
public AvailabilityStatus isRemoteServerAvailable() {
    Configuration config = configurationService.getConfiguration();
    if (!isRemoteServerConfigured(config)) {
        return new AvailabilityStatus(false, "Remote server is not configured", HttpStatus.BAD_GATEWAY);
    }
    String url = systemSettingManager.getSystemSetting(SettingKey.REMOTE_INSTANCE_URL) + PING_PATH;
    String username = (String) systemSettingManager.getSystemSetting(SettingKey.REMOTE_INSTANCE_USERNAME);
    String password = (String) systemSettingManager.getSystemSetting(SettingKey.REMOTE_INSTANCE_PASSWORD);
    log.debug(String.format("Remote server ping URL: %s, username: %s", url, username));
    HttpEntity<String> request = getBasicAuthRequestEntity(username, password);
    ResponseEntity<String> response = null;
    HttpStatus sc = null;
    String st = null;
    AvailabilityStatus status = null;
    try {
        response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        sc = response.getStatusCode();
    } catch (HttpClientErrorException ex) {
        sc = ex.getStatusCode();
        st = ex.getStatusText();
    } catch (HttpServerErrorException ex) {
        sc = ex.getStatusCode();
        st = ex.getStatusText();
    } catch (ResourceAccessException ex) {
        return new AvailabilityStatus(false, "Network is unreachable", HttpStatus.BAD_GATEWAY);
    }
    log.debug("Response status code: " + sc);
    if (HttpStatus.FOUND.equals(sc)) {
        status = new AvailabilityStatus(false, "No authentication was provided", sc);
    } else if (HttpStatus.UNAUTHORIZED.equals(sc)) {
        status = new AvailabilityStatus(false, "Authentication failed", sc);
    } else if (HttpStatus.INTERNAL_SERVER_ERROR.equals(sc)) {
        status = new AvailabilityStatus(false, "Remote server experienced an internal error", sc);
    } else if (HttpStatus.OK.equals(sc)) {
        status = new AvailabilityStatus(true, "Authentication was successful", sc);
    } else {
        status = new AvailabilityStatus(false, "Server is not available: " + st, sc);
    }
    log.info("Status: " + status);
    return status;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Configuration(org.hisp.dhis.configuration.Configuration) HttpStatus(org.springframework.http.HttpStatus) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) ResourceAccessException(org.springframework.web.client.ResourceAccessException)

Example 64 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project apollo by ctripcorp.

the class CtripUserServiceTest method testSearchUsersWithError.

@Test(expected = HttpClientErrorException.class)
public void testSearchUsersWithError() throws Exception {
    when(restTemplate.exchange(eq(someUserServiceUrl), eq(HttpMethod.POST), any(HttpEntity.class), eq(someResponseType))).thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
    String someKeyword = "someKeyword";
    int someOffset = 0;
    int someLimit = 10;
    ctripUserService.searchUsers(someKeyword, someOffset, someLimit);
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) Test(org.junit.Test) AbstractUnitTest(com.ctrip.framework.apollo.portal.AbstractUnitTest)

Example 65 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project x-pipe by ctripcorp.

the class RetryableRestOperationsTest method retryableRestOperationsFailWithMethodNotSupportedTest.

@Test
public void retryableRestOperationsFailWithMethodNotSupportedTest() {
    RestOperations restOperations = RestTemplateFactory.createCommonsHttpRestTemplate();
    try {
        restOperations.put(generateRequestURL("/test"), null);
        fail();
    } catch (Exception e) {
        assertTrue(e instanceof HttpClientErrorException);
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestOperations(org.springframework.web.client.RestOperations) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) ResourceAccessException(org.springframework.web.client.ResourceAccessException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Test(org.junit.Test) AbstractTest(com.ctrip.xpipe.AbstractTest)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)109 HttpHeaders (org.springframework.http.HttpHeaders)31 Test (org.junit.Test)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 HashMap (java.util.HashMap)21 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)21 MediaType (org.springframework.http.MediaType)19 RestTemplate (org.springframework.web.client.RestTemplate)19 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)18 HttpEntity (org.springframework.http.HttpEntity)16 URI (java.net.URI)15 Map (java.util.Map)8 HttpStatus (org.springframework.http.HttpStatus)8 RestClientException (org.springframework.web.client.RestClientException)8 ResourceAccessException (org.springframework.web.client.ResourceAccessException)7 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)6 Date (java.util.Date)5 List (java.util.List)5 OpenAppNamespaceDTO (com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO)4 ArrayList (java.util.ArrayList)4