Example usage for org.springframework.web.client HttpStatusCodeException getResponseBodyAsString

List of usage examples for org.springframework.web.client HttpStatusCodeException getResponseBodyAsString

Introduction

In this page you can find the example usage for org.springframework.web.client HttpStatusCodeException getResponseBodyAsString.

Prototype

public String getResponseBodyAsString() 

Source Link

Document

Return the response body as a string.

Usage

From source file:org.openlmis.fulfillment.service.BaseCommunicationServiceTest.java

@Test
public void shouldRetryObtainingAccessToken() throws Exception {
    // given/*from  ww w . j  av  a2s.  c o  m*/
    BaseCommunicationService<T> service = prepareService();
    HttpStatusCodeException exception = mock(HttpStatusCodeException.class);
    when(exception.getStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED);
    when(exception.getResponseBodyAsString())
            .thenReturn("{\"error\":\"invalid_token\",\"error_description\":\"" + UUID.randomUUID() + "}");

    // when
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class),
            eq(service.getArrayResultClass()))).thenThrow(exception);

    expectedException.expect(DataRetrievalException.class);
    service.findAll("", RequestParameters.init());

    verify(authService, times(1)).clearTokenCache();
    verify(authService, times(2)).obtainAccessToken();
}

From source file:com.auditbucket.client.AbRestClient.java

public String getErrorMessage(HttpStatusCodeException e) {

    if (e.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
        logger.error(e.getResponseBodyAsString());
        return e.getResponseBodyAsString();
    }/*from   w ww  . j ava  2 s  . com*/

    JsonNode n = null;
    try {
        n = mapper.readTree(e.getResponseBodyAsByteArray());
    } catch (IOException e1) {

        logger.error(String.valueOf(e1));
    }
    String message;
    if (n != null)
        message = String.valueOf(n.get("message"));
    else
        message = e.getMessage();

    return message;
}

From source file:eu.cloudwave.wp5.feedback.eclipse.base.infrastructure.rest.RestClientImpl.java

private void handleErrors(final RestClientException exception) {
    // handle 404 NOT FOUND error
    if (exception instanceof ResourceAccessException) {
        throw new RequestException(ErrorType.FEEDBACK_HANDLER_NOT_AVAILABLE, exception.getMessage());
    } else if (exception instanceof HttpStatusCodeException) {
        final HttpStatusCodeException httpException = (HttpStatusCodeException) exception;

        // handle 404 NOT FOUND error
        if (httpException.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw new RequestException(ErrorType.FEEDBACK_HANDLER_NOT_AVAILABLE, exception.getMessage());
        }/*from ww w . ja va  2s .  c  o m*/

        // handle other errors
        final ObjectMapper mapper = new ObjectMapper();
        try {
            final RestRequestErrorDto error = mapper.readValue(httpException.getResponseBodyAsString(),
                    RestRequestErrorDto.class);
            throw new RequestException(error.getType(), error.getMessage());
        } catch (final IOException e) {
        }
    }
    throw new RuntimeException(READ_SERVER_ERROR_EXCEPTION, exception);
}

From source file:eu.cloudwave.wp5.feedbackhandler.metricsources.NewRelicClient.java

/**
 * {@inheritDoc}//from   w  w w  .  j ava 2s .  c om
 */
@Override
protected void handleHttpServerException(final HttpStatusCodeException serverError)
        throws MetricSourceClientException, IOException {
    // if the status code is 401 UNAUTHORIZED -> the API key is not valid
    if (serverError.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
        throw new MetricSourceClientException(ErrorType.NEW_RELIC__INVALID_API_KEY,
                Messages.ERRORS__NEW_RELIC__INVALID_API_KEY);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode errorNode = mapper.readTree(serverError.getResponseBodyAsString());
    final JsonNode titleNode = errorNode.findValue(JSON__TITLE);
    if (titleNode != null) {
        final String message = titleNode.asText();
        ErrorType type = ErrorType.NEW_RELIC__GENERAL;

        if (message.contains(ERROR__INVALID_APPLICATION_ID)
                || message.equals(ERROR__INVALID_PARAMETER_APPLICATION_ID)) {
            type = ErrorType.NEW_RELIC__INVALID_APPLICATION_ID;
        } else if (message.contains(ERROR__UNKNOWN_METRIC)) {
            type = ErrorType.UNKNOWN_METRIC;
        } else if (message.contains(ERROR__INVALID_PARAMETER)) {
            type = ErrorType.INVALID_PARAMETER;
        }
        throw new MetricSourceClientException(type, message);
    }
}

From source file:org.springframework.vault.authentication.AuthenticationStepsExecutor.java

@Override
@SuppressWarnings("unchecked")
public VaultToken login() throws VaultException {

    Object state = null;/* ww  w  . j a  v a  2  s.  c o m*/

    for (Node<?> o : chain.steps) {

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Executing %s with current state %s", o, state));
        }

        try {
            if (o instanceof HttpRequestNode) {
                state = doHttpRequest((HttpRequestNode<Object>) o, state);
            }

            if (o instanceof AuthenticationSteps.MapStep) {
                state = doMapStep((MapStep<Object, Object>) o, state);
            }

            if (o instanceof OnNextStep) {
                state = doOnNext((OnNextStep<Object>) o, state);
            }

            if (o instanceof AuthenticationSteps.SupplierStep<?>) {
                state = doSupplierStep((SupplierStep<Object>) o);
            }

            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Executed %s with current state %s", o, state));
            }
        } catch (HttpStatusCodeException e) {
            throw new VaultException(
                    String.format("HTTP request %s in state %s failed with Status %s and body %s", o, state,
                            e.getStatusCode(), VaultResponses.getError(e.getResponseBodyAsString())));
        } catch (RuntimeException e) {
            throw new VaultException(String.format("Authentication execution failed in %s", o), e);
        }
    }

    if (state instanceof VaultToken) {
        return (VaultToken) state;
    }

    if (state instanceof VaultResponse) {

        VaultResponse response = (VaultResponse) state;
        Assert.state(response.getAuth() != null, "Auth field must not be null");
        return LoginTokenUtil.from(response.getAuth());
    }

    throw new IllegalStateException(
            String.format("Cannot retrieve VaultToken from authentication chain. Got instead %s", state));
}

From source file:org.springframework.vault.authentication.AwsIamAuthentication.java

@SuppressWarnings("unchecked")
private VaultToken createTokenUsingAwsIam() {

    Map<String, String> login = new HashMap<>();

    login.put("iam_http_request_method", "POST");
    login.put("iam_request_url", Base64Utils.encodeToString(options.getEndpointUri().toString().getBytes()));
    login.put("iam_request_body", REQUEST_BODY_BASE64_ENCODED);

    String headerJson = getSignedHeaders(options);

    login.put("iam_request_headers", Base64Utils.encodeToString(headerJson.getBytes()));

    if (!StringUtils.isEmpty(options.getRole())) {
        login.put("role", options.getRole());
    }//from   w w  w.  j a v a 2s.  c o  m

    try {

        VaultResponse response = this.vaultRestOperations.postForObject("auth/{mount}/login", login,
                VaultResponse.class, options.getPath());

        Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");

        if (logger.isDebugEnabled()) {

            if (response.getAuth().get("metadata") instanceof Map) {
                Map<Object, Object> metadata = (Map<Object, Object>) response.getAuth().get("metadata");
                logger.debug(
                        String.format("Login successful using AWS-IAM authentication for user id %s, ARN %s",
                                metadata.get("client_user_id"), metadata.get("canonical_arn")));
            } else {
                logger.debug("Login successful using AWS-IAM authentication");
            }
        }

        return LoginTokenUtil.from(response.getAuth());
    } catch (HttpStatusCodeException e) {
        throw new VaultException(String.format("Cannot login using AWS-IAM: %s",
                VaultResponses.getError(e.getResponseBodyAsString())));
    }
}