Example usage for org.springframework.http.client ClientHttpResponse getBody

List of usage examples for org.springframework.http.client ClientHttpResponse getBody

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpResponse getBody.

Prototype

InputStream getBody() throws IOException;

Source Link

Document

Return the body of the message as an input stream.

Usage

From source file:nu.yona.server.rest.RestClientErrorHandler.java

private Optional<ErrorResponseDto> getYonaErrorResponse(ClientHttpResponse response) {
    try {//from   w  w  w  .  j a v  a2  s. c  o m
        if (getStatusCode(response).series() == HttpStatus.Series.CLIENT_ERROR) {
            return Optional.ofNullable(objectMapper.readValue(response.getBody(), ErrorResponseDto.class));
        }
    } catch (IOException e) {
        // Ignore and just return empty
    }
    return Optional.empty();
}

From source file:org.springframework.social.weibo.api.impl.WeiboErrorHandler.java

private Map<String, String> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    String json = readFully(response.getBody());

    System.out.println(json);//  w ww  . j  a v  a  2 s .co m

    if (logger.isDebugEnabled()) {
        logger.debug("Error from Weibo: " + json);
    }

    try {
        return mapper.<Map<String, String>>readValue(json, new TypeReference<Map<String, String>>() {
        });
    } catch (JsonParseException e) {
        return null;
    }
}

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

@Test
public void dispatchesConsumedResponseAgain() throws IOException {
    final RestTemplate template = new RestTemplate();
    final MockRestServiceServer server = MockRestServiceServer.createServer(template);

    server.expect(requestTo(url)).andRespond(withUnauthorizedRequest().body(new byte[] { 0x13, 0x37 }));

    template.setErrorHandler(new OAuth2ErrorHandler(new OAuth2CompatibilityResponseErrorHandler(), null));
    final Rest rest = Rest.create(template);

    final ClientHttpResponse response = rest.execute(GET, url).dispatch(status(), on(UNAUTHORIZED).capture())
            .to(ClientHttpResponse.class);

    assertThat(response.getBody().available(), is(2));
}

From source file:com.appglu.impl.SyncTemplate.java

/**
 * {@inheritDoc}//from   w  w w  .  ja  v a 2  s  .c o  m
 */
public void downloadChangesForTables(final List<TableVersion> tables,
        final InputStreamCallback inputStreamCallback) throws AppGluRestClientException {
    RequestCallback requestCallback = new RequestCallback() {
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(new TableVersionBody(tables));

            HttpHeaders requestHeaders = requestEntity.getHeaders();
            if (!requestHeaders.isEmpty()) {
                request.getHeaders().putAll(requestHeaders);
            }

            jsonMessageConverter.write(requestEntity.getBody(), requestHeaders.getContentType(), request);
        }
    };

    ResponseExtractor<Object> responseExtractor = new ResponseExtractor<Object>() {
        public Object extractData(ClientHttpResponse response) throws IOException {
            inputStreamCallback.doWithInputStream(response.getBody());
            return null;
        }
    };

    try {
        this.restOperations.execute(CHANGES_FOR_TABLES_URL, HttpMethod.POST, requestCallback,
                responseExtractor);
    } catch (RestClientException e) {
        throw new AppGluRestClientException(e.getMessage(), e);
    }
}

From source file:org.bremersee.common.web.client.ResponseErrorHandlerImpl.java

/**
 * Find a throwable instance by parsing the response to a {@link ThrowableMessageDto}.
 *
 * @param response the HTTP response as JSON
 * @return the throwable/*from w w w.j  a  v a2  s  . c  om*/
 * @throws IOException if the response cannot be parsed
 */
protected Throwable findThrowableFromJson(final ClientHttpResponse response) throws IOException {
    final ThrowableMessageDto dto = objectMapper.readValue(response.getBody(), ThrowableMessageDto.class);
    if (log.isDebugEnabled()) {
        log.debug("Got throwable from response json body: " + dto);
    }
    return ExceptionRegistry.getExceptionByDto(dto);
}

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))));
    }/*from w w w.j a v  a  2  s .  c o 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.springframework.social.wechat.api.impl.WechatErrorHandler.java

private Map<String, String> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    String json = readFully(response.getBody());

    logger.debug("Error from Wechat: " + json);

    try {//from w  w  w .  j  a va2  s  .  c om
        Map<String, String> responseMap = mapper.<Map<String, String>>readValue(json,
                new TypeReference<Map<String, String>>() {
                });
        Map<String, String> errorMap = Collections.<String, String>emptyMap();
        errorMap.put(ERROR_CODE, responseMap.get(ERROR_CODE));
        errorMap.put(ERROR_MESSAGE, responseMap.get(ERROR_MESSAGE));
        return errorMap;

    } catch (JsonParseException e) {
        return null;
    }
}

From source file:com.apress.prospringintegration.customadapters.inbound.pollerdriven.StockPollingMessageSource.java

protected Stock getStockInformationFor(final String symbol) {
    String url = String.format(this.stockServiceUrl, symbol);
    Stock stock = restTemplate.execute(url, HttpMethod.GET, null, new ResponseExtractor<Stock>() {
        @Override/*from   ww  w.j  a  va 2 s  . c  o m*/
        public Stock extractData(ClientHttpResponse clientHttpResponse) throws IOException {
            String fragPattern = String.format(jsonFragmentTemplate, symbol, symbol);
            String bodyAsText = IOUtils.toString(clientHttpResponse.getBody());

            int indexOfMatch = bodyAsText.indexOf(fragPattern);

            if (indexOfMatch != -1) {
                String sectionContainingPrice = bodyAsText.substring(indexOfMatch);
                Matcher matcher = symbolSize.matcher(sectionContainingPrice);

                StringBuilder stringBuilder = new StringBuilder();

                while (matcher.find()) {
                    stringBuilder.append(matcher.group(1)).append(".").append(matcher.group(2));
                }

                String response = stringBuilder.toString();
                Float fl = Float.parseFloat(response);

                return new Stock(symbol, fl);
            }

            return null;
        }
    });

    return stock;
}

From source file:com.jaspersoft.jasperserver.api.security.externalAuth.sso.SsoTicketValidatorImpl.java

/**
 * Override this method to handle a response in any format other than XML
 *
 * @param response// ww w .ja v a  2s.c  o m
 * @return
 */
protected String getPrincipalNameFromSsoResponse(ClientHttpResponse response) {
    try {
        DOMParser domParser = new DOMParser();
        domParser.parse(new InputSource(response.getBody()));
        String principalXmlTagName = getExternalAuthProperties().getCustomSsoProperty(PRINCIPAL_XML_TAG_NAME);
        NodeList nodeList = domParser.getDocument().getElementsByTagName(principalXmlTagName);
        if (nodeList == null || nodeList.getLength() == 0) {
            logger.warn("Could not find principal xml tag in the SSO server response.");
            throw new AuthenticationServiceException("SSO Authentication failed");
        }

        return nodeList.item(0).getTextContent();
    } catch (Exception e) {
        logger.error("Failed to get principal from the SSO server response", e);
        throw new AuthenticationServiceException(e.getMessage(), e);
    }
}

From source file:org.springframework.social.cloudplaylists.api.impl.CloudPlaylistsErrorHandler.java

@SuppressWarnings("rawtypes")
private Map extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    try {/* w  ww .ja  v a  2s  . com*/
        String json = readFully(response.getBody());
        HashMap errorDetails = mapper.readValue(json, HashMap.class);
        return errorDetails;
    } catch (JsonParseException e) {
        return null;
    }
}