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:com.appglu.impl.StorageTemplate.java

protected boolean streamStorageFile(StorageFile file, final InputStreamCallback inputStreamCallback,
        RequestCallback requestCallback) throws AppGluRestClientException {
    URI uri = this.getStorageFileURI(file);

    try {/*from w  w w . ja  va 2  s .  c o m*/
        ResponseExtractor<Boolean> responseExtractor = new ResponseExtractor<Boolean>() {
            public Boolean extractData(ClientHttpResponse response) throws IOException {
                if (response.getStatusCode() == HttpStatus.NOT_MODIFIED) {
                    return false;
                }

                Md5DigestCalculatingInputStream inputStream = new Md5DigestCalculatingInputStream(
                        response.getBody());
                inputStreamCallback.doWithInputStream(inputStream);

                String eTagHeader = response.getHeaders().getETag();

                if (StringUtils.isNotEmpty(eTagHeader)) {
                    String eTag = StringUtils.removeDoubleQuotes(eTagHeader);

                    byte[] contentMd5 = inputStream.getMd5Digest();
                    if (!HashUtils.md5MatchesWithETag(contentMd5, eTag)) {
                        throw new AppGluRestClientException("Unable to verify integrity of downloaded file. "
                                + "Client calculated content hash didn't match hash calculated by server");
                    }
                }

                return true;
            }
        };

        return this.downloadRestOperations.execute(uri, HttpMethod.GET, requestCallback, responseExtractor);
    } catch (RestClientException e) {
        throw new AppGluRestClientException(e.getMessage(), e);
    }
}

From source file:org.springframework.social.twitter.api.impl.TwitterErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    if (statusCode.series() == Series.SERVER_ERROR) {
        handleServerErrors(statusCode);// w ww  .jav a 2 s  .c  o m
    } else if (statusCode.series() == Series.CLIENT_ERROR) {
        handleClientErrors(response);
    }

    // if not otherwise handled, do default handling and wrap with UncategorizedApiException
    try {
        super.handleError(response);
    } catch (Exception e) {
        throw new UncategorizedApiException("twitter", "Error consuming Twitter REST API", e);
    }
}

From source file:org.echocat.marquardt.authority.AuthorityIntegrationTest.java

private void doPost(final String url, final Object content) throws Exception {
    final byte[] bytes;
    try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        _objectMapper.writeValue(byteArrayOutputStream, content);
        byteArrayOutputStream.flush();// w w  w .  j a v  a2s.com
        bytes = byteArrayOutputStream.toByteArray();
    }
    final URI urlToPost = new URI(url);
    final ClientHttpRequest request = new OkHttpClientHttpRequestFactory().createRequest(urlToPost,
            HttpMethod.POST);
    request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.getHeaders().add(X_CERTIFICATE.getHeaderName(), Base64.encodeBase64URLSafeString(CERTIFICATE));
    request.getBody().write(bytes);
    final ClientHttpResponse response = request.execute();
    _status = response.getStatusCode().value();
    try (final InputStream inputStream = response.getBody()) {
        try (final InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8)) {
            _response = CharStreams.toString(inputStreamReader);
        }
    }
}

From source file:com.kite9.k9server.LoggingInterceptor.java

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Request: %s %s %s", request.getMethod(), request.getURI(),
                new String(body, getCharset(request))));
    }//  w ww.  ja  va2s.  co  m

    ClientHttpResponse response = execution.execute(request, body);

    if (log.isDebugEnabled()) {
        log.debug(String.format("Response: %s %s", response.getStatusCode().value(),
                copyToString(response.getBody(), getCharset(response))));
    }

    return response;
}

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

private ResponseEntity<I> toResponseEntity(final I entity, final ClientHttpResponse response)
        throws IOException {
    return new ResponseEntity<>(entity, response.getHeaders(), response.getStatusCode());
}

From source file:cz.jirutka.spring.http.client.cache.internal.SizeLimitedHttpResponseReader.java

private InMemoryClientHttpResponse createInMemoryResponse(ClientHttpResponse originalResponse,
        ByteArrayOutputStream body) throws IOException {

    HttpStatus status = originalResponse.getStatusCode();
    HttpHeaders headers = originalResponse.getHeaders();

    return new InMemoryClientHttpResponse(body.toByteArray(), status, headers);
}

From source file:org.springframework.social.twitter.api.impl.TwitterErrorHandler.java

private void handleClientErrors(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);

    String errorText = "";
    if (errorMap.containsKey("error")) {
        errorText = (String) errorMap.get("error");
    } else if (errorMap.containsKey("errors")) {
        Object errors = errorMap.get("errors");
        if (errors instanceof List) {
            @SuppressWarnings("unchecked")
            List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
            errorText = errorsList.get(0).get("message");
        } else if (errors instanceof String) {
            errorText = (String) errors;
        }//from  w  ww. ja  v  a  2  s  .c  om
    }

    if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorText.contains("Rate limit exceeded.")) {
            throw new RateLimitExceededException("twitter");
        }
    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (errorText == null) {
            throw new NotAuthorizedException("twitter", response.getStatusText());
        } else if (errorText.equals("Could not authenticate you.")) {
            throw new MissingAuthorizationException("twitter");
        } else if (errorText.equals("Could not authenticate with OAuth.")) { // revoked token
            throw new RevokedAuthorizationException("twitter");
        } else if (errorText.equals("Invalid / expired Token")) { // Note that Twitter doesn't actually expire tokens
            throw new InvalidAuthorizationException("twitter", errorText);
        } else {
            throw new NotAuthorizedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.FORBIDDEN) {
        if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
            throw new DuplicateStatusException("twitter", errorText);
        } else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
            throw new MessageTooLongException(errorText);
        } else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
            throw new InvalidMessageRecipientException(errorText);
        } else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
            throw new RateLimitExceededException("twitter");
        } else {
            throw new OperationNotPermittedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("twitter", errorText);
    } else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM)
            || statusCode == HttpStatus.valueOf(TOO_MANY_REQUESTS)) {
        throw new RateLimitExceededException("twitter");
    }

}

From source file:org.springframework.cloud.dataflow.shell.command.HttpCommands.java

private RestTemplate createRestTemplate(final StringBuilder buffer) {
    RestTemplate restTemplate = new RestTemplate();

    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        @Override/* w ww .  j av  a2  s .  co  m*/
        public boolean hasError(ClientHttpResponse response) throws IOException {
            HttpStatus status = response.getStatusCode();
            return (status == HttpStatus.BAD_GATEWAY || status == HttpStatus.GATEWAY_TIMEOUT
                    || status == HttpStatus.INTERNAL_SERVER_ERROR);
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            outputError(response.getStatusCode(), buffer);
        }
    });

    return restTemplate;
}

From source file:pl.sgorecki.facebook.marketing.ads.impl.FacebookAdsErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    FacebookError error = extractErrorFromResponse(response);
    handleFacebookError(response.getStatusCode(), error);
}

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java

private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode;//from  w w w  .j a  va2 s . c o  m
    try {
        statusCode = response.getStatusCode();
    } catch (IllegalArgumentException ex) {
        throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
                response.getHeaders(), getResponseBody(response), getCharset(response));
    }
    return statusCode;
}