Search in sources :

Example 6 with HttpServerErrorException

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

the class SmsGateway method send.

public HttpStatus send(String urlTemplate, HttpEntity<?> request, Class<?> klass) {
    ResponseEntity<?> response;
    HttpStatus statusCode = null;
    try {
        response = restTemplate.exchange(urlTemplate, HttpMethod.POST, request, klass);
        statusCode = response.getStatusCode();
    } catch (HttpClientErrorException ex) {
        log.error("Client error", ex);
        statusCode = ex.getStatusCode();
    } catch (HttpServerErrorException ex) {
        log.error("Server error", ex);
        statusCode = ex.getStatusCode();
    } catch (Exception ex) {
        log.error("Error", ex);
        statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
    }
    log.info("Response status code: " + statusCode);
    return statusCode;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpStatus(org.springframework.http.HttpStatus) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException)

Example 7 with HttpServerErrorException

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

the class BulkSmsGateway method send.

private OutboundMessageResponse send(UriComponentsBuilder uriBuilder) {
    ResponseEntity<String> responseEntity = null;
    try {
        URI url = uriBuilder.build().encode("ISO-8859-1").toUri();
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
    } catch (HttpClientErrorException ex) {
        log.error("Client error " + ex.getMessage());
    } catch (HttpServerErrorException ex) {
        log.error("Server error " + ex.getMessage());
    } catch (Exception ex) {
        log.error("Error " + ex.getMessage());
    }
    return getResponse(responseEntity);
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) URI(java.net.URI) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException)

Example 8 with HttpServerErrorException

use of org.springframework.web.client.HttpServerErrorException in project spring-framework by spring-projects.

the class UndertowXhrTransport method createReceiveCallback.

private ClientCallback<ClientExchange> createReceiveCallback(final TransportRequest transportRequest, final URI url, final HttpHeaders headers, final XhrClientSockJsSession sockJsSession, final SettableListenableFuture<WebSocketSession> connectFuture) {
    return new ClientCallback<ClientExchange>() {

        @Override
        public void completed(final ClientExchange exchange) {
            exchange.setResponseListener(new ClientCallback<ClientExchange>() {

                @Override
                public void completed(ClientExchange result) {
                    ClientResponse response = result.getResponse();
                    if (response.getResponseCode() != 200) {
                        HttpStatus status = HttpStatus.valueOf(response.getResponseCode());
                        IoUtils.safeClose(result.getConnection());
                        onFailure(new HttpServerErrorException(status, "Unexpected XHR receive status"));
                    } else {
                        SockJsResponseListener listener = new SockJsResponseListener(transportRequest, result.getConnection(), url, headers, sockJsSession, connectFuture);
                        listener.setup(result.getResponseChannel());
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("XHR receive headers: " + toHttpHeaders(response.getResponseHeaders()));
                    }
                    try {
                        StreamSinkChannel channel = result.getRequestChannel();
                        channel.shutdownWrites();
                        if (!channel.flush()) {
                            channel.getWriteSetter().set(ChannelListeners.<StreamSinkChannel>flushingChannelListener(null, null));
                            channel.resumeWrites();
                        }
                    } catch (IOException exc) {
                        IoUtils.safeClose(result.getConnection());
                        onFailure(exc);
                    }
                }

                @Override
                public void failed(IOException exc) {
                    IoUtils.safeClose(exchange.getConnection());
                    onFailure(exc);
                }
            });
        }

        @Override
        public void failed(IOException exc) {
            onFailure(exc);
        }

        private void onFailure(Throwable failure) {
            if (connectFuture.setException(failure)) {
                return;
            }
            if (sockJsSession.isDisconnected()) {
                sockJsSession.afterTransportClosed(null);
            } else {
                sockJsSession.handleTransportError(failure);
                sockJsSession.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
            }
        }
    };
}
Also used : ClientExchange(io.undertow.client.ClientExchange) ClientResponse(io.undertow.client.ClientResponse) ClientCallback(io.undertow.client.ClientCallback) HttpStatus(org.springframework.http.HttpStatus) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) IOException(java.io.IOException) CloseStatus(org.springframework.web.socket.CloseStatus) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException)

Example 9 with HttpServerErrorException

use of org.springframework.web.client.HttpServerErrorException in project spring-boot by spring-projects.

the class CloudFoundrySecurityService method getAccessLevel.

/**
	 * Return the access level that should be granted to the given token.
	 * @param token the token
	 * @param applicationId the cloud foundry application ID
	 * @return the access level that should be granted
	 * @throws CloudFoundryAuthorizationException if the token is not authorized
	 */
public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException {
    try {
        URI uri = getPermissionsUri(applicationId);
        RequestEntity<?> request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build();
        Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody();
        if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) {
            return AccessLevel.FULL;
        }
        return AccessLevel.RESTRICTED;
    } catch (HttpClientErrorException ex) {
        if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
        }
        throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex);
    } catch (HttpServerErrorException ex) {
        throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) URI(java.net.URI) HashMap(java.util.HashMap) Map(java.util.Map) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException)

Example 10 with HttpServerErrorException

use of org.springframework.web.client.HttpServerErrorException 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)

Aggregations

HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)12 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)8 HttpStatus (org.springframework.http.HttpStatus)5 ResourceAccessException (org.springframework.web.client.ResourceAccessException)4 HttpHeaders (org.springframework.http.HttpHeaders)3 IOException (java.io.IOException)2 URI (java.net.URI)2 Date (java.util.Date)2 Configuration (org.hisp.dhis.configuration.Configuration)2 ImportSummariesResponseExtractor (org.hisp.dhis.dxf2.common.ImportSummariesResponseExtractor)2 Events (org.hisp.dhis.dxf2.events.event.Events)2 ImportSummaries (org.hisp.dhis.dxf2.importsummary.ImportSummaries)2 ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)2 Test (org.junit.Test)2 ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)2 RequestCallback (org.springframework.web.client.RequestCallback)2 ClientCallback (io.undertow.client.ClientCallback)1 ClientExchange (io.undertow.client.ClientExchange)1 ClientResponse (io.undertow.client.ClientResponse)1 UnknownHostException (java.net.UnknownHostException)1