Java Code Examples for org.springframework.http.client.ClientHttpResponse#getStatusCode()

The following examples show how to use org.springframework.http.client.ClientHttpResponse#getStatusCode() . 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: RegistryAuthInterceptor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
                                    final ClientHttpRequestExecution execution) throws IOException {
    final HttpHeaders headers = request.getHeaders();
    ClientHttpResponse execute = execution.execute(request, body);

    if (execute.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        List<String> list = execute.getHeaders().get("Www-Authenticate");
        if (!CollectionUtils.isEmpty(list)) {
            String tokenString = list.get(0);
            RegistryAuthAdapter.AuthContext ctx = new RegistryAuthAdapter.AuthContext(headers,
              HttpHeaders.readOnlyHttpHeaders(headers),
              tokenString);
            adapter.handle(ctx);
            return execution.execute(request, body);
        }
    }
    return execute;
}
 
Example 2
Source File: CloudControllerResponseErrorHandler.java    From cf-java-client-sap with Apache License 2.0 6 votes vote down vote up
private static CloudOperationException getException(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    String statusText = response.getStatusText();

    ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally

    if (response.getBody() != null) {
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> responseBody = mapper.readValue(response.getBody(), Map.class);
            String description = getTrimmedDescription(responseBody);
            return new CloudOperationException(statusCode, statusText, description);
        } catch (IOException e) {
            // Fall through. Handled below.
        }
    }
    return new CloudOperationException(statusCode, statusText);
}
 
Example 3
Source File: RestErrorHandler.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@Override public void handleError(ClientHttpResponse response)
        throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    switch (statusCode.series()) {
        case CLIENT_ERROR:
            LOGGER.error("Client Error! response: status code: {}, status text: {}, header: {}, body: {}, charset: {}",
                    statusCode.value(), response.getStatusText(), response.getHeaders(), Arrays.toString(getResponseBody(response)), getCharset(response));
            throw new HttpRestTemplateException(String.valueOf(statusCode.value()), statusCode.value() + " " + response.getStatusText());
        case SERVER_ERROR:
            LOGGER.error("Server Error! response: status code: {}, status text: {}, header: {}, body: {}, charset: {}",
                    statusCode.value(), response.getStatusText(), response.getHeaders(), Arrays.toString(getResponseBody(response)), getCharset(response));
            throw new HttpRestTemplateException(String.valueOf(statusCode.value()), statusCode.value() + " " + response.getStatusText());
        default:
            throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}
 
Example 4
Source File: WxResponseErrorHandler.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
    try {
        return response.getStatusCode();
    } catch (IllegalArgumentException ex) {
        throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
                response.getHeaders(), getResponseBody(response), getCharset(response));
    }
}
 
Example 5
Source File: DCTMJacksonErrorHandler.java    From documentum-rest-client-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    MediaType mediaType = response.getHeaders().getContentType();
    RestError error = null;
    for(HttpMessageConverter converter : converters) {
        if(converter.canRead(JsonRestError.class, mediaType)) {
            error = (RestError)converter.read(JsonRestError.class, response);
            break;
        }
    }
    throw new DCTMRestErrorException(response.getHeaders(), response.getStatusCode(), error);
}
 
Example 6
Source File: RetryAttemptsResponseHeaderSetter.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    ClientHttpResponse response = execution.execute(request, body);
    HttpResponse httpResponse = new HttpResponse(response.getStatusCode());
    HttpHeaders headers = copyHeaders(response.getHeaders());
    headers.set("Retry-Attempts", valueOf(attempt.incrementAndGet()));
    httpResponse.setHeaders(headers);
    httpResponse.setBody(toByteArray(response.getBody()));
    return httpResponse;
}
 
Example 7
Source File: DefaultResponseErrorHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode;
	try {
		statusCode = response.getStatusCode();
	}
	catch (IllegalArgumentException ex) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(),
				response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response));
	}
	return statusCode;
}
 
Example 8
Source File: LoginErrorHandler.java    From moVirt with Apache License 2.0 5 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus code = response.getStatusCode();
    switch (code.series()) {
        case REDIRECTION:
            URI location = URIUtils.getURIWithoutParameters(response.getHeaders().getLocation());
            String message = context.getString(R.string.login_server_send_redirect,
                    (location == null ? "" : location.toString()));
            throw new LoginRedirectException(code, message);
        default:
            super.handleError(response);
            break;
    }
}
 
Example 9
Source File: JsonRpcResponseErrorHandler.java    From jsonrpc4j with MIT License 5 votes vote down vote up
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	final HttpStatus statusCode;
	try {
		statusCode = response.getStatusCode();
	} catch (IllegalArgumentException ex) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(),
				response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response));
	}
	return statusCode;
}
 
Example 10
Source File: JvmServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public JvmHttpRequestResult pingAndUpdateJvmState(final Jvm jvm) {
    ClientHttpResponse response = null;
    JvmState jvmState = jvm.getState();
    String responseDetails = StringUtils.EMPTY;
    try {
        response = clientFactoryHelper.requestGet(jvm.getStatusUri());
        LOGGER.info(">>> Response = {} from jvm {}", response.getStatusCode(), jvm.getId().getId());
        jvmState = JvmState.JVM_STARTED;
        if (response.getStatusCode() == HttpStatus.OK) {
            jvmStateService.updateState(jvm, jvmState, StringUtils.EMPTY);
        } else {
            // As long as we get a response even if it's not a 200 it means that the JVM is alive
            jvmStateService.updateState(jvm, jvmState, StringUtils.EMPTY);
            responseDetails = MessageFormat.format("Request {0} sent expecting a response code of {1} but got {2} instead",
                    jvm.getStatusUri(), HttpStatus.OK.value(), response.getRawStatusCode());

        }
    } catch (final IOException ioe) {
        LOGGER.info(ioe.getMessage(), ioe);
        jvmStateService.updateState(jvm, JvmState.JVM_STOPPED, StringUtils.EMPTY);
        responseDetails = MessageFormat.format("Request {0} sent and got: {1}", jvm.getStatusUri(), ioe.getMessage());
        jvmState = JvmState.JVM_STOPPED;
    } catch (RuntimeException rte) {
        LOGGER.error(rte.getMessage(), rte);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return new JvmHttpRequestResult(jvmState, responseDetails);
}
 
Example 11
Source File: DefaultResponseErrorHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the HTTP status of the given response.
 * @param response the response to inspect
 * @return the associated HTTP status
 * @throws IOException in case of I/O errors
 * @throws UnknownHttpStatusCodeException in case of an unknown status code
 * that cannot be represented with the {@link HttpStatus} enum
 * @since 4.3.8
 */
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	try {
		return response.getStatusCode();
	}
	catch (IllegalArgumentException ex) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
}
 
Example 12
Source File: RestClientResponseErrorHandler.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode;
    try {
        statusCode = response.getStatusCode();
    } catch (IllegalArgumentException ex) {
        if (L.isDebugEnabled()) {
            L.debug(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0014"), ex);
        }
        throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
            response.getHeaders(), getResponseBody(response), getCharset(response));
    }
    return statusCode;
}
 
Example 13
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
    return new ResponseExtractor<ResponseEntity<Void>>() {
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            return new ResponseEntity(response.getHeaders(), response.getStatusCode());
        }
    };
}
 
Example 14
Source File: CloudControllerResponseErrorHandler.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    switch (statusCode.series()) {
        case CLIENT_ERROR:
        case SERVER_ERROR:
            throw getException(response);
        default:
            throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}
 
Example 15
Source File: TokenRefreshingClientHttpRequestFactory.java    From google-plus-java-api with Apache License 2.0 5 votes vote down vote up
public ClientHttpResponse execute() throws IOException {
    ClientHttpResponse response = delegate.execute();
    if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        logger.info("Token is invalid (got 401 response). Trying get a new token using the refresh token");

        String newToken = callback.refreshToken();
        if (newToken == null) {
            return response;
        } else {
            logger.info("New token obtained, retrying the request with it");
            // reflectively set the new token at the oauth2 interceptor (no nicer way, alas)
            for (ClientHttpRequestInterceptor interceptor: requestInterceptors) {
                if (interceptor.getClass().getName().equals("org.springframework.social.oauth2.OAuth2RequestInterceptor")) {
                    Field field = ReflectionUtils.findField(interceptor.getClass(), "accessToken");
                    field.setAccessible(true);
                    ReflectionUtils.setField(field, interceptor, newToken);
                }
            }

            // create a new request, using the new token, but don't go through the refreshing factory again
            // because it may cause an endless loop if all tokens are invalid
            ClientHttpRequest newRequest = TokenRefreshingClientHttpRequestFactory.this.delegate.createRequest(delegate.getURI(), delegate.getMethod());
            return newRequest.execute();
        }
    }
    return response;
}
 
Example 16
Source File: NestedDispatchTest.java    From riptide with MIT License 4 votes vote down vote up
private void fail(final ClientHttpResponse response) throws IOException {
    throw new Failure(response.getStatusCode());
}
 
Example 17
Source File: FailsafePluginRetriesTest.java    From riptide with MIT License 4 votes vote down vote up
@SneakyThrows
private boolean isBadGateway(@Nullable final ClientHttpResponse response) {
    return response != null && response.getStatusCode() == HttpStatus.BAD_GATEWAY;
}
 
Example 18
Source File: JwtSsoResponseErrorHandler.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    if (!HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) {
        errorHandler.handleError(response);
    } else {
        ClientHttpResponse bufferedResponse = new ClientHttpResponse() {
            private byte[] lazyBody;

            public HttpStatus getStatusCode() throws IOException {
                return response.getStatusCode();
            }

            public synchronized InputStream getBody() throws IOException {
                if (lazyBody == null) {
                    InputStream bodyStream = response.getBody();
                    if (bodyStream != null) {
                        lazyBody = FileCopyUtils.copyToByteArray(bodyStream);
                    } else {
                        lazyBody = new byte[0];
                    }
                }
                return new ByteArrayInputStream(lazyBody);
            }

            public HttpHeaders getHeaders() {
                return response.getHeaders();
            }

            public String getStatusText() throws IOException {
                return response.getStatusText();
            }

            public void close() {
                response.close();
            }

            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
        };

        List<String> authenticateHeaders = bufferedResponse.getHeaders()
                .get(JwtSsoClientContext.HEADER_WWW_AUTHENTICATE);
        if (authenticateHeaders != null) {
            for (String authenticateHeader : authenticateHeaders) {
                if (authenticateHeader.startsWith(JwtSsoClientContext.PREFIX_BEARER_TOKEN)) {
                    throw new JwtSsoAccessTokenRequiredException("access token required.");
                }
            }
        }
        errorHandler.handleError(bufferedResponse);
    }

}
 
Example 19
Source File: LicenceController.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, value = "/licence/{licenceId}/generate")
public @ResponseBody Object generateLicence(@PathVariable Long licenceId) throws Exception {
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = AuthenticationService.currentActingUser();
        Licence licence = Licence.findByIdAndCompanyId(licenceId, user.getCompany().getId());
        if (licence.getStatus() == LicenceStatus.NEW) {
            if (licence.getPageLayout() == PageLayout.PHOTOCOPY) {
                String filename = FilenameUtils.concat(licenceFileService.getLicencedPdfFileFolder(), licence.getId() + ".pdf");
                licenceInvoiceService.generateOutletInvoice(licence, filename);
                licence.setStatus(LicenceStatus.GENERATED);
                licence.merge();
                map.put("result", true);
            } else {
                ClientHttpResponse serverResponse = RestHttpClientFactory.execute("rest/licence/generate/" + licence.getId(), HttpMethod.GET);
                InputStream inputStream = serverResponse.getBody();
                try {
                    if (serverResponse.getStatusCode() == HttpStatus.OK) {
                        Response response = new ObjectMapper().readValue(inputStream, Response.class);
                        if (response.getStatus() == ResponseStatus.OK) {
                            map.put("result", true);
                        } else {
                            map.put("result", false);
                            map.put("message", response.getResponseObject());
                        }
                    } else {
                        map.put("result", false);
                        map.put("message", "Error generating licence");
                    }
                } finally {
                    inputStream.close();
                }
            }
        } else {
            map.put("result", false);
            map.put("message", "Licence already generated");
        }
        return map;
    } catch (Exception e) {
        logger.error("Unable to generate licenceid: " + licenceId, e);
        throw e;
    }
}
 
Example 20
Source File: HeimdallResponseErrorHandler.java    From heimdall with Apache License 2.0 3 votes vote down vote up
/**
 * Determine the HTTP status of the given response.
 * <p>Note: Only called from {@link #handleError}, not from {@link #hasError}.
 * @param response the response to inspect
 * @return the associated HTTP status
 * @throws IOException in case of I/O errors
 * @throws UnknownHttpStatusCodeException in case of an unknown status code
 * that cannot be represented with the {@link HttpStatus} enum
 * @since 4.3.8
 */
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	try {
		return response.getStatusCode();
	}
	catch (IllegalArgumentException ex) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
}