Example usage for org.springframework.http.client ClientHttpResponse getStatusCode

List of usage examples for org.springframework.http.client ClientHttpResponse getStatusCode

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpResponse getStatusCode.

Prototype

HttpStatus getStatusCode() throws IOException;

Source Link

Document

Return the HTTP status code as an HttpStatus enum value.

Usage

From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpClientImpl.java

@Override
public boolean redirectRequest(final String requestUrl) throws IOException {

    final boolean result = true;
    final RestTemplate restTemplate = new RestTemplate();

    final java.net.URI uri = java.net.URI.create(requestUrl);
    final java.awt.Desktop dp = java.awt.Desktop.getDesktop();
    if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
        dp.browse(uri);/*from w  w  w  . j  a va  2 s.c  om*/
    }
    restTemplate.execute(requestUrl, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(final ClientHttpRequest request) throws IOException {
            // empty block should be documented
        }
    }, new ResponseExtractor<Object>() {
        @Override
        public Object extractData(final ClientHttpResponse response) throws IOException {
            final HttpStatus statusCode = response.getStatusCode();
            LOG.debug("Response status: " + statusCode.toString());
            return response.getStatusCode();
        }
    });
    return result;
}

From source file:org.zalando.riptide.RouterTest.java

@Test
public void shouldCatchIOExceptionFromBinding() throws IOException {
    exception.expect(RestClientException.class);
    exception.expectCause(instanceOf(IOException.class));

    final Optional<HttpStatus> anyStatus = Optional.empty();
    final Binding<HttpStatus> binding = create(anyStatus, (response, converters) -> {
        throw new IOException();
    });/*w  ww.  j a  va2  s . c  o  m*/

    final ClientHttpResponse response = mock(ClientHttpResponse.class);
    when(response.getStatusCode()).thenReturn(OK);

    unit.route(response, emptyList(), status(), singletonList(binding));
}

From source file:com.miserablemind.api.consumer.tradeking.api.impl.StreamingTemplate.java

private StreamReader createStream(HttpMethod method, String streamUrl, MultiValueMap<String, String> body,
        List<StreamListener> listeners) throws StreamCreationException {
    try {/*w ww  .ja  va2s.  c o  m*/
        ClientHttpResponse response = executeRequest(method, streamUrl, body);
        if (response.getStatusCode().value() > 200) {
            throw new StreamCreationException("Unable to create stream", response.getStatusCode());
        }
        return new StreamReaderImpl(response.getBody(), listeners);
    } catch (IOException e) {
        throw new StreamCreationException("Unable to create stream.", e);
    }
}

From source file:fr.itldev.koya.services.impl.util.AlfrescoRestErrorHandler.java

@Override
public void handleError(ClientHttpResponse clienthttpresponse) throws IOException {

    if (!statusOK.contains(clienthttpresponse.getStatusCode())) {
        AlfrescoServiceException ex;//from ww w .  java 2  s  . co m
        if (clienthttpresponse.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
            java.util.Scanner s = new java.util.Scanner(clienthttpresponse.getBody()).useDelimiter("\\A");
            String message = s.hasNext() ? s.next() : "";

            /*
             Try to get any Koya Error code if exists
             */
            Integer koyaErrorCode = null;

            Matcher matcher = ERRORCODEPATTERN.matcher(message);
            if (matcher.find()) {
                koyaErrorCode = Integer.valueOf(matcher.group(1));
            }

            ex = new AlfrescoServiceException(
                    "Erreur " + clienthttpresponse.getStatusCode() + " : " + clienthttpresponse.getStatusText(),
                    koyaErrorCode);
            ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value());
        } else if (clienthttpresponse.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            ex = new AlfrescoServiceException("Acces Denied");
            ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value());

        } else {
            ex = new AlfrescoServiceException();
            ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value());
            throw ex;
        }
        throw ex;

    }
}

From source file:co.mafiagame.telegraminterface.inputhandler.UpdateController.java

private void setErrorHandler(RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        @Override//from w w  w.ja  v a 2s  .c om
        public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
            return !clientHttpResponse.getStatusCode().equals(HttpStatus.OK);
        }

        @Override
        public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
            logger.error("error calling telegram getUpdate\n code:{}\n{}", clientHttpResponse.getStatusCode(),
                    IOUtils.toString(clientHttpResponse.getBody()));
        }
    });
}

From source file:tools.AssertingRestTemplate.java

public AssertingRestTemplate() {
    setErrorHandler(new DefaultResponseErrorHandler() {
        @Override//from  w ww.  j  a v  a 2s  .  c o m
        public void handleError(ClientHttpResponse response) throws IOException {
            if (hasError(response)) {
                log.error("Response has status code [" + response.getStatusCode() + "] and text ["
                        + response.getStatusText() + "])");
            }
        }
    });
}

From source file:org.zalando.riptide.NestedDispatchTest.java

private void fail(final ClientHttpResponse response) throws IOException {
    throw new Failure(response.getStatusCode());
}

From source file:nl.gridshore.nosapi.impl.NosApiResponseErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    logger.debug("Handle error '{}' received from the NOS server.", response.getStatusCode().name());
    HttpStatus statusCode = response.getStatusCode();
    MediaType contentType = response.getHeaders().getContentType();
    Charset charset = contentType != null ? contentType.getCharSet() : null;
    byte[] body = FileCopyUtils.copyToByteArray(response.getBody());

    switch (statusCode) {
    case BAD_REQUEST:
    case UNAUTHORIZED:
    case FORBIDDEN:
        throwClientException(charset, body);
    default:/*from   w  ww  .  j av a  2  s . c  om*/
        // do nothing, let the series resolving do it' work
    }

    switch (statusCode.series()) {
    case CLIENT_ERROR:
        throw new HttpClientErrorException(statusCode, response.getStatusText(), body, charset);
    case SERVER_ERROR:
        throw new HttpServerErrorException(statusCode, response.getStatusText(), body, charset);
    default:
        throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}

From source file:org.cloudfoundry.client.lib.rest.LoggingRestTemplate.java

@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
        final ResponseExtractor<T> responseExtractor) throws RestClientException {
    final String[] status = new String[1];
    final HttpStatus[] httpStatus = new HttpStatus[1];
    final Object[] headers = new Object[1];
    final String[] message = new String[1];
    T results = null;//from  ww w. j  a  v a  2  s  . com
    RestClientException exception = null;
    try {
        results = super.doExecute(url, method, requestCallback, new ResponseExtractor<T>() {
            @SuppressWarnings("rawtypes")
            public T extractData(ClientHttpResponse response) throws IOException {
                httpStatus[0] = response.getStatusCode();
                headers[0] = response.getHeaders();
                T data = null;
                if (responseExtractor != null && (data = responseExtractor.extractData(response)) != null) {
                    if (data instanceof String) {
                        message[0] = ((String) data).length() + " bytes";
                    } else if (data instanceof Map) {
                        message[0] = ((Map) data).keySet().toString();
                    } else {
                        message[0] = data.getClass().getName();
                    }
                    return data;
                } else {
                    message[0] = "<no data>";
                    return null;
                }
            }
        });
        status[0] = "OK";
    } catch (RestClientException e) {
        status[0] = "ERROR";
        message[0] = e.getMessage();
        exception = e;
        if (e instanceof HttpStatusCodeException) {
            httpStatus[0] = ((HttpStatusCodeException) e).getStatusCode();
        }
    }
    addLogMessage(method, url, status[0], httpStatus[0], message[0]);
    if (exception != null) {
        throw exception;
    }
    return results;
}

From source file:org.syncope.client.validation.SyncopeClientErrorHandler.java

@Override
public void handleError(final ClientHttpResponse response) throws IOException {

    if (!ArrayUtils.contains(MANAGED_STATUSES, response.getStatusCode())) {
        super.handleError(response);
    }//from  w  w w .j av  a2s  .  c o m

    List<String> exceptionTypesInHeaders = response.getHeaders().get(EXCEPTION_TYPE_HEADER);
    if (exceptionTypesInHeaders == null) {
        LOG.debug("No " + EXCEPTION_TYPE_HEADER + " provided");

        return;
    }

    SyncopeClientCompositeErrorException compositeException = new SyncopeClientCompositeErrorException(
            response.getStatusCode());

    Set<String> handledExceptions = new HashSet<String>();
    for (String exceptionTypeAsString : exceptionTypesInHeaders) {
        SyncopeClientExceptionType exceptionType = null;
        try {
            exceptionType = SyncopeClientExceptionType.getFromHeaderValue(exceptionTypeAsString);
        } catch (IllegalArgumentException e) {
            LOG.error("Unexpected value of " + EXCEPTION_TYPE_HEADER + ": " + exceptionTypeAsString, e);
        }
        if (exceptionType != null) {
            handledExceptions.add(exceptionTypeAsString);

            SyncopeClientException clientException = new SyncopeClientException();
            clientException.setType(exceptionType);
            if (response.getHeaders().get(exceptionType.getElementHeaderName()) != null
                    && !response.getHeaders().get(exceptionType.getElementHeaderName()).isEmpty()) {

                clientException.setElements(response.getHeaders().get(exceptionType.getElementHeaderName()));
            }

            compositeException.addException(clientException);
        }
    }

    exceptionTypesInHeaders.removeAll(handledExceptions);
    if (!exceptionTypesInHeaders.isEmpty()) {
        LOG.error("Unmanaged exceptions: " + exceptionTypesInHeaders);
    }

    if (compositeException.hasExceptions()) {
        throw compositeException;
    }
}