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:io.pivotal.xd.chaoslemur.reporter.DataDogReporter.java

@Override
public void sendEvent(String title, String message) {
    Map<String, Object> payload = new HashMap<>();
    payload.put("title", title);
    payload.put("text", message);
    payload.put("tags", this.tags);

    try {//from   w  ww. j  av  a  2 s .c o m
        this.restTemplate.postForEntity(URI, payload, Void.class, this.apiKey, this.appKey);
    } catch (HttpClientErrorException e) {
        this.logger.error(e.getResponseBodyAsString());
    }
}

From source file:com.ge.predix.test.utils.ACSTestUtil.java

public void assertExceptionResponseBody(final HttpClientErrorException e, final String message) {
    String responseBody = e.getResponseBodyAsString();
    Assert.assertNotNull(responseBody);/*  w w  w  .  j  av  a  2 s . com*/
    Assert.assertTrue(responseBody.contains(message),
            String.format("Expected=[%s], Actual=[%s]", message, responseBody));
}

From source file:io.pivotal.strepsirrhini.chaoslemur.reporter.DataDogReporter.java

@Override
public void sendEvent(Event event) {
    Map<String, Object> payload = new HashMap<>();
    payload.put("title", title(event.getIdentifier()));
    payload.put("text", message(event.getMembers()));
    payload.put("tags", this.tags);

    try {/*from w w w.  j a  v a2s .  c o m*/
        this.restTemplate.postForEntity(URI, payload, Void.class, this.apiKey, this.appKey);
    } catch (HttpClientErrorException e) {
        this.logger.warn(e.getResponseBodyAsString());
    }
}

From source file:com.recursivechaos.clearent.service.ClearentService.java

public Transaction postTransaction(Transaction transaction) {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Response> responseEntity;
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.set("api-key", gatewayProperties.getKey());
    HttpEntity<String> request = new HttpEntity<>(transaction.toString(), headers);
    try {/*from  w  w  w.ja  va 2s .  co m*/
        responseEntity = restTemplate.postForEntity(gatewayProperties.getUrl() + "/transactions", request,
                Response.class);
    } catch (HttpClientErrorException he) {
        logger.error("Gateway Request Failed: {}", he.getLocalizedMessage());
        logger.error(he.getResponseBodyAsString());
        throw new GatewayException(he.getLocalizedMessage());
    }
    assert responseEntity != null;
    return responseEntity.getBody().getPayload().getTransaction();
}

From source file:com.codeabovelab.dm.cluman.cluster.registry.DockerRegistryAuthAdapter.java

@SuppressWarnings("unchecked")
private String getToken(AuthInfo authInfo) {
    RegistryCredentials registryCredentials = provider.getRegistryCredentials();
    // realm="https://auth.docker.io/token",service="registry.docker.io"
    // get https://auth.docker.io/token?service=registry.docker.io
    try {/*from  ww w. ja va 2s  .c  om*/
        URI path = getPath(authInfo);
        HttpEntity<String> request = null;
        if (checkCredentials()) {
            request = new HttpEntity<>(createHeaders(registryCredentials));
        }
        Map<String, String> token = restTemplate.exchange(path, HttpMethod.GET, request, Map.class).getBody();

        if (!token.isEmpty()) {
            return token.get("token");
        }
    } catch (HttpClientErrorException e) {
        log.error("Can't do request " + e.getResponseBodyAsString(), e);
    } catch (Exception e) {
        log.error("Can't do request", e);
    }
    return null;
}

From source file:dk.skogemann.airline.project.ApiController.java

@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<JsonError> handleHttpClientException(HttpClientErrorException e) {
    e.printStackTrace();/*from w  w w. java 2s.c  o m*/
    JsonError msg = new JsonError();
    msg.setMessage(e.getResponseBodyAsString());
    return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
}

From source file:com.marklogic.mgmt.admin.AdminManager.java

public void init(String licenseKey, String licensee) {
    final URI uri = adminConfig.buildUri("/admin/v1/init");

    String json = null;/*from   w w  w.  j  a v  a2 s. com*/
    if (licenseKey != null && licensee != null) {
        json = format("{\"license-key\":\"%s\", \"licensee\":\"%s\"}", licenseKey, licensee);
    } else {
        json = "{}";
    }
    final String payload = json;

    logger.info("Initializing MarkLogic at: " + uri);
    invokeActionRequiringRestart(new ActionRequiringRestart() {
        @Override
        public boolean execute() {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<String>(payload, headers);
            try {
                ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, entity,
                        String.class);
                logger.info("Initialization response: " + response);
                // According to http://docs.marklogic.com/REST/POST/admin/v1/init, a 202 is sent back in the event a
                // restart is needed. A 400 or 401 will be thrown as an error by RestTemplate.
                return HttpStatus.ACCEPTED.equals(response.getStatusCode());
            } catch (HttpClientErrorException hcee) {
                String body = hcee.getResponseBodyAsString();
                if (logger.isTraceEnabled()) {
                    logger.trace("Response body: " + body);
                }
                if (body != null && body.contains("MANAGE-ALREADYINIT")) {
                    logger.info("MarkLogic has already been initialized");
                    return false;
                } else {
                    logger.error("Caught error, response body: " + body);
                    throw hcee;
                }
            }
        }
    });
}

From source file:com.alexshabanov.springrestapi.ControllerMockTest.java

@Test
public void shouldGetBadRequest() throws IOException {
    doThrow(IllegalArgumentException.class).when(profileController).deleteProfile(id);
    when(profileController.handleIllegalArgumentException()).thenReturn(errorDesc);

    try {/*  w  w  w.j  ava2s .c o m*/
        restClient.delete(path(CONCRETE_PROFILE_RESOURCE), id);
        fail();
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
        final ErrorDesc actual = getObjectMapper().reader(ErrorDesc.class)
                .readValue(e.getResponseBodyAsString());
        assertEquals(errorDesc, actual);
    }
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

public String createOrcid(String email, String givenNames, String familyName)
        throws OrcidException, OrcidEmailExistsException, OrcidHttpException {

    String newOrcid = null;/*w  ww  . j  a v a 2s.  co m*/

    log.debug("Creating ORCID...");
    log.debug("email: " + email);
    log.debug("givenNames: " + givenNames);
    log.debug("familyName: " + familyName);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");
    headers.set("Content-Type", "application/vdn.orcid+xml");
    headers.set("Authorization", "Bearer " + orcidCreateToken);

    OrcidMessage message = new OrcidMessage();
    message.setEmail(email);
    message.setGivenNames(givenNames);
    message.setFamilyName(familyName);
    message.setMessageVersion(orcidMessageVersion);
    //TODO Affiliation should be set based on organization once faculty from more than one organization are processed
    message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT);
    message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER);
    message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER);
    message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO);
    message.setAffiliationOrganizationAddressCountry(OrcidMessage.US);
    message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER);
    message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD);

    HttpEntity entity = new HttpEntity(message, headers);

    log.debug("Configured RestTemplate Message Converters...");
    List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters();
    for (HttpMessageConverter<?> converter : converters) {
        log.debug("converter: " + converter);
        log.debug("supported media types: " + converter.getSupportedMediaTypes());
        log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(String.class, MediaType.APPLICATION_XML));
        log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML));
    }

    log.debug("Request headers: " + headers);

    HttpStatus responseStatusCode = null;
    String responseBody = null;

    try {
        if (useTestHttpProxy.equalsIgnoreCase("TRUE")) {
            log.info("Using HTTP ***TEST*** proxy...");
            System.setProperty("http.proxyHost", testHttpProxyHost);
            System.setProperty("http.proxyPort", testHttpProxyPort);
            log.info("http.proxyHost: " + System.getProperty("http.proxyHost"));
            log.info("http.proxyPort: " + System.getProperty("http.proxyPort"));
        }
        ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity,
                String.class);
        responseStatusCode = responseEntity.getStatusCode();
        responseBody = responseEntity.getBody();
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        URI locationURI = responseHeaders.getLocation();
        String uriString = locationURI.toString();
        newOrcid = extractOrcid(uriString);
        log.debug("HTTP response status code: " + responseStatusCode);
        log.debug("HTTP response headers:     " + responseHeaders);
        log.debug("HTTP response body:        " + responseBody);
        log.debug("HTTP response location:    " + locationURI);
        log.debug("New ORCID:                 " + newOrcid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
            log.debug(e.getStatusCode());
            log.debug(e.getResponseBodyAsString());
            log.debug(e.getMessage());
            throw new OrcidEmailExistsException(e);
        }
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }

    return newOrcid;
}

From source file:gov.fda.open.demo.service.FDADataProxyServiceImpl.java

/**
 * Queries <b>openFDA</b> using RESTFul Service.
 * // w w w .ja v  a 2  s  .com
 * @see <a href="https://open.fda.gov/drug/event/">Drug Adverse Events</a>
 * @see gov.fda.open.demo.service.FDADataProxyService#getDrugAdverseSummary(gov.fda.open.demo.model.request.GetDrugAdverseSummaryRequest)
 */
@Loggable(LogLevel.INFO)
@Override
public GetDrugAdverseSummaryResponse getDrugAdverseSummary(GetDrugAdverseSummaryRequest request) {

    // Build search term from the request object
    String searchTerm = buildSearchTerm(request);

    Map<String, String> params = new HashMap<String, String>();
    params.put("searchTerm", searchTerm);
    params.put("appKey", appKey);
    params.put("limit", String.valueOf(limit));

    boolean success = true;
    int skip = 0, total = 0;
    String errorCode = null, message = null;
    DrugFrequency[] reactionFrequencies = null;

    // Get the summary
    SummaryType summaryType = request.getSummaryType();
    // Max total records to be fetched
    int totalFetch = request.getMaxFetchCnt();
    DrugResultsAggregator drugResultAggregrator = new DrugResultsAggregator(summaryType);
    try {
        do {
            params.put("skip", String.valueOf(skip));
            // Build drug events URI
            URI httpUri = buildDrugEventsRequestURI(params);
            // Execute
            String responseBody = template.getForObject(httpUri, String.class);
            // Parse the JSON node
            JsonNode jRootNode = mapper.readTree(responseBody);
            if (jRootNode.has("error") == false) {
                total = jRootNode.get("meta").get("results").get("total").asInt(0);
            } else {
                JsonNode jErrorNode = jRootNode.get("error");
                errorCode = jErrorNode.get("code").asText();
                message = jErrorNode.get("message").asText();
                // Log the error
                success = false;
                break;
            }

            JsonNode resultsNode = jRootNode.get("results");
            drugResultAggregrator.aggregate(resultsNode);

            skip += limit;
        } while (total > skip && skip < totalFetch);

        // Get aggregated results
        Map<Date, Map<String, Integer>> aggregateResults = drugResultAggregrator.getResults();
        // Build the Drug frequency
        reactionFrequencies = new DrugFrequency[aggregateResults.size()];
        List<Date> dates = new ArrayList<Date>(aggregateResults.keySet());
        // Sort the date keys
        Collections.sort(dates);
        int i = 0;
        for (Date date : dates) {
            reactionFrequencies[i++] = new DrugFrequency(date, aggregateResults.get(date));
        }
    } catch (HttpClientErrorException e) {
        LOG.debug("Open FDA returned error", e);
        success = false;
        String jsonResponse = e.getResponseBodyAsString();
        LOG.error(" Exception response {} ", jsonResponse);
        try {
            JsonNode jErrorNode = mapper.readTree(jsonResponse).get("error");
            errorCode = jErrorNode.get("code").asText();
            message = jErrorNode.get("message").asText();
        } catch (IOException ex) {
            LOG.error("Client side error", ex);
            errorCode = "404";
            message = "Json parser error";
        }
    } catch (IOException | RestClientException e) {
        LOG.error("Error occurred", e);
        throw new ApplicationException(e);
    }

    GetDrugAdverseSummaryResponse response = new GetDrugAdverseSummaryResponse(success, errorCode, message,
            reactionFrequencies);
    if (reactionFrequencies != null && total > totalFetch) {
        response.setMessage(String.format("You are viewing \"%d\" of \"%d\" results", totalFetch, total));
    }

    return response;
}