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

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

Introduction

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

Prototype

public String getResponseBodyAsString() 

Source Link

Document

Return the response body as a string.

Usage

From source file:org.apache.zeppelin.livy.LivyHelper.java

protected String executeHTTP(String targetURL, String method, String jsonData, String paragraphId)
        throws Exception {
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    RestTemplate restTemplate = getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("X-Requested-By", "zeppelin");
    ResponseEntity<String> response = null;
    try {/*w w w . j ava2 s  .  c  om*/
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
            paragraphHttpMap.put(paragraphId, response);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
            paragraphHttpMap.put(paragraphId, response);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                e.getResponseBodyAsString()));
    }
    if (response == null) {
        return null;
    }

    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201
            || response.getStatusCode().value() == 404) {
        return response.getBody();
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
        throw new Exception(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
    }
}

From source file:org.apereo.portal.events.tincan.providers.DefaultTinCanAPIProvider.java

/**
 * Initialize the API.  Just sends an initialization event to the LRS provider.
 * This uses the activities/state API to do the initial test.
 *///w w w  . j a  v a  2s . c o m
@Override
public void init() {
    loadConfig();

    if (!isEnabled()) {
        return;
    }

    try {
        String actorStr = format(ACTOR_FORMAT, actorName, actorEmail);

        // Setup GET params...
        List<BasicNameValuePair> getParams = new ArrayList<>();
        getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId));
        getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr));
        getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId));

        Object body = null;
        if (formEncodeActivityData) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED);
            map.add(activitiesFormParamName, json);
            body = map;

        } else {
            // just post a simple:  {"status": "started"} record to the states API to verify
            // the service is up.
            Map<String, String> data = new HashMap<String, String>();
            data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED);
            body = data;
        }

        ResponseEntity<Object> response = sendRequest(STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body,
                Object.class);
        if (response.getStatusCode().series() != Series.SUCCESSFUL) {
            logger.error("LRS provider for URL " + LRSUrl
                    + " it not configured properly, or is offline.  Disabling provider.");
        }

        // todo: Need to think through a strategy for handling errors submitting
        // to the LRS.
    } catch (HttpClientErrorException e) {
        // log some additional info in this case...
        logger.error("LRS provider for URL " + LRSUrl
                + " failed to contact LRS for initialization.  Disabling provider.", e);
        logger.error("  Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
        enabled = false;

    } catch (Exception e) {
        logger.error("LRS provider for URL " + LRSUrl
                + " failed to contact LRS for initialization.  Disabling provider", e);
        enabled = false;
    }
}

From source file:org.cloudfoundry.identity.uaa.login.EmailResetPasswordService.java

@Override
public void forgotPassword(String email) {
    String subject = getSubjectText();
    String htmlContent = null;//from   ww w .ja  v a 2  s.co  m
    String userId = null;
    try {
        ResponseEntity<Map<String, String>> response = passwordResetEndpoints.resetPassword(email);
        if (response.getStatusCode() == HttpStatus.CONFLICT) {
            //TODO - file story to refactor and not swallow all errors below
            htmlContent = getResetUnavailableEmailHtml(email);
            userId = response.getBody().get("user_id");
        } else if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
            //TODO noop - previous implementation just logged an error
        } else {
            userId = response.getBody().get("user_id");
            htmlContent = getCodeSentEmailHtml(response.getBody().get("code"), email);
        }
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.CONFLICT) {
            htmlContent = getResetUnavailableEmailHtml(email);
            try {
                Map<String, String> body = new ObjectMapper().readValue(e.getResponseBodyAsString(),
                        new TypeReference<Map<String, String>>() {
                        });
                userId = body.get("user_id");
            } catch (IOException ioe) {
                logger.error("Bad response from UAA", ioe);
            }

        } else {
            logger.info("Exception raised while creating password reset for " + email, e);
        }
    } catch (IOException e) {
        logger.error("Exception raised while creating password reset for " + email, e);
    }

    if (htmlContent != null && userId != null) {
        messageService.sendMessage(userId, email, MessageType.PASSWORD_RESET, subject, htmlContent);
    }
}

From source file:org.opentestsystem.authoring.testspecbank.client.TestSpecBankClient.java

@Override
public Optional<ValidationError> deleteTestSpecification(final String testSpecificationKey) {
    Optional<ValidationError> maybeValidationError = Optional.empty();
    final URI uri = UriComponentsBuilder
            .fromUriString(String.format("%stestSpecification/%s", baseUri, testSpecificationKey)).build()
            .toUri();/*from www.  j  a va 2 s  .c  o m*/

    try {
        tsbOauthRestTemplate.delete(uri);
    } catch (final HttpClientErrorException hce) {
        LOGGER.error("Error deleting {0} test specification: ", hce);
        if (hce.getStatusCode() == HttpStatus.UNPROCESSABLE_ENTITY) {
            try {
                // The NoContentResponseResource contains an array of ValidationErrors.  If we got to this point,
                // the TestSpecificationController#deleteTestSpecification endpoint will have returned a
                // NoContentResponseResource with a single ValidationError describing what went wrong.
                final NoContentResponseResource response = objectMapper.readValue(hce.getResponseBodyAsString(),
                        NoContentResponseResource.class);
                maybeValidationError = Optional.of(response.getErrors()[0]);
            } catch (final Exception mapEx) {
                LOGGER.error(String.format("Error mapping response %s to ValidationError: ",
                        hce.getResponseBodyAsString()), mapEx);
                final String errorMessage = mapEx.getMessage() == null ? mapEx.getClass().getName()
                        : mapEx.getMessage();
                maybeValidationError = Optional.of(new ValidationError("mapping exception", errorMessage));
            }
        } else {
            maybeValidationError = Optional.of(new ValidationError("client exception", hce.getMessage()));
        }
    } catch (final Exception e) {
        LOGGER.error("Error deleting {0} test specification: ", e);
        maybeValidationError = Optional.of(new ValidationError("server exception", e.getMessage()));
    }

    return maybeValidationError;
}

From source file:org.springframework.cloud.netflix.metrics.atlas.AtlasMetricObserver.java

private void sendMetricsBatch(List<Metric> metrics) {
    try {/*w w  w  . ja v a 2s.  c  o m*/
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        JsonGenerator gen = smileFactory.createGenerator(output, JsonEncoding.UTF8);

        gen.writeStartObject();

        writeCommonTags(gen);
        if (writeMetrics(gen, metrics) == 0)
            return; // short circuit this batch if no valid/numeric metrics existed

        gen.writeEndObject();
        gen.flush();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/x-jackson-smile"));
        HttpEntity<byte[]> entity = new HttpEntity<>(output.toByteArray(), headers);
        try {
            restTemplate.exchange(uri, HttpMethod.POST, entity, Map.class);
        } catch (HttpClientErrorException e) {
            logger.error("Failed to write metrics to atlas: " + e.getResponseBodyAsString(), e);
        } catch (RestClientException e) {
            logger.error("Failed to write metrics to atlas", e);
        }
    } catch (IOException e) {
        // an IOException stemming from the generator writing to a
        // ByteArrayOutputStream is impossible
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.social.connect.web.ConnectSupport.java

/**
 * Complete the connection to the OAuth2 provider.
 * @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory
 * @param request the current web request
 * @return a new connection to the service provider
 *///from   ww w  .  ja  v  a  2s.c om
public Connection<?> completeConnection(OAuth2ConnectionFactory<?> connectionFactory,
        NativeWebRequest request) {
    if (connectionFactory.supportsStateParameter()) {
        verifyStateParameter(request);
    }

    String code = request.getParameter("code");
    try {
        AccessGrant accessGrant = connectionFactory.getOAuthOperations().exchangeForAccess(code,
                callbackUrl(request), null);
        return connectionFactory.createConnection(accessGrant);
    } catch (HttpClientErrorException e) {
        logger.warn("HttpClientErrorException while completing connection: " + e.getMessage());
        logger.warn("      Response body: " + e.getResponseBodyAsString());
        throw e;
    }
}

From source file:org.springframework.web.client.RestTemplateIntegrationTests.java

@Test
public void notFound() {
    try {/*  ww w .j a va 2 s  . com*/
        template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
        fail("HttpClientErrorException expected");
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
        assertNotNull(ex.getStatusText());
        assertNotNull(ex.getResponseBodyAsString());
    }
}