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:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

@Override
public void downloadFile(Linkable<GenologicsFile> file, OutputStream resultStream) throws IOException {
    if (file == null) {
        throw new IllegalArgumentException("file cannot be null");
    }/*from  ww w .j a v a 2 s  .com*/
    if (resultStream == null) {
        throw new IllegalArgumentException("resultStream cannot be null");
    }

    GenologicsEntity entityAnno = checkEntityAnnotated(GenologicsFile.class);

    GenologicsFile realFile;
    if (file instanceof GenologicsFile) {
        realFile = (GenologicsFile) file;
        if (realFile.getContentLocation() == null) {
            // Don't know where the actual file is, so fetch to get the full info.
            realFile = retrieve(file.getUri(), GenologicsFile.class);
        }
    } else {
        realFile = retrieve(file.getUri(), GenologicsFile.class);
    }

    URI fileURL;
    if (downloadDirectFromHttpStore && HTTP_PROTOCOLS.contains(realFile.getContentLocation().getScheme())) {
        fileURL = realFile.getContentLocation();
    } else {
        try {
            fileURL = new URI(
                    getServerApiAddress() + entityAnno.uriSection() + "/" + realFile.getLimsid() + "/download");
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(
                    "File LIMS id " + realFile.getLimsid() + " produces an invalid URI for download.", e);
        }
    }

    logger.info("Downloading {}", fileURL);

    ClientHttpRequest request = httpRequestFactory.createRequest(fileURL, HttpMethod.GET);

    ClientHttpResponse response = request.execute();

    switch (response.getStatusCode().series()) {
    case SUCCESSFUL:
        try (InputStream in = response.getBody()) {
            byte[] buffer = new byte[8192];
            IOUtils.copyLarge(in, resultStream, buffer);
        } finally {
            resultStream.flush();
        }
        logger.debug("{} download successful.", fileURL);
        break;

    default:
        logger.debug("{} download failed. HTTP {}", fileURL, response.getStatusCode());
        throw new IOException("Could not download file " + realFile.getLimsid() + " (HTTP "
                + response.getStatusCode() + "): " + response.getStatusText());
    }
}

From source file:org.apache.geode.management.internal.web.http.support.HttpRequester.java

HttpRequester(Properties securityProperties, RestTemplate restTemplate) {
    final SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
    this.securityProperties = securityProperties;
    if (restTemplate == null) {
        this.restTemplate = new RestTemplate(clientHttpRequestFactory);
    } else {/* www .j ava  2 s  .  co  m*/
        this.restTemplate = restTemplate;
    }

    // add our custom HttpMessageConverter for serializing DTO Objects into the HTTP request message
    // body and de-serializing HTTP response message body content back into DTO Objects
    List<HttpMessageConverter<?>> converters = this.restTemplate.getMessageConverters();
    // remove the MappingJacksonHttpConverter
    for (int i = converters.size() - 1; i >= 0; i--) {
        HttpMessageConverter converter = converters.get(i);
        if (converter instanceof MappingJackson2HttpMessageConverter) {
            converters.remove(converter);
        }
    }
    converters.add(new SerializableObjectHttpMessageConverter());

    this.restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            String body = IOUtils.toString(response.getBody(), StandardCharsets.UTF_8);
            final String message = String.format("The HTTP request failed with: %1$d - %2$s.",
                    response.getRawStatusCode(), body);

            if (response.getRawStatusCode() == 401) {
                throw new AuthenticationFailedException(message);
            } else if (response.getRawStatusCode() == 403) {
                throw new NotAuthorizedException(message);
            } else {
                throw new RuntimeException(message);
            }
        }
    });
}

From source file:org.apache.geode.management.internal.web.http.support.HttpRequester.java

Object extractResponse(ClientHttpResponse response) throws IOException {
    MediaType mediaType = response.getHeaders().getContentType();
    if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        return org.apache.commons.io.IOUtils.toString(response.getBody(), "UTF-8");
    } else {/*from  w  w w  . jav  a 2s .c om*/
        Path tempFile = Files.createTempFile("fileDownload", "");
        if (tempFile.toFile().exists()) {
            FileUtils.deleteQuietly(tempFile.toFile());
        }
        Files.copy(response.getBody(), tempFile);
        return tempFile;
    }
}

From source file:org.craftercms.commons.rest.HttpMessageConvertingResponseErrorHandler.java

protected String getResponseBodyAsString(ClientHttpResponse response) throws IOException {
    return IOUtils.toString(response.getBody(), response.getHeaders().getContentType().getCharset());
}

From source file:org.cruk.genologics.api.GenologicsAPIBatchOperationTest.java

@Test
public void testArtifactBatchFetch() throws Exception {
    List<LimsLink<Artifact>> links = new ArrayList<LimsLink<Artifact>>();

    links.add(new ArtifactLink(new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/2-1000624")));
    links.add(new ArtifactLink(new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/2-1000622")));
    links.add(new ArtifactLink(new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/2-1000605")));
    links.add(new ArtifactLink(new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/2-1000623")));
    links.add(new ArtifactLink(new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/2-1000625")));

    File expectedResultFile = new File("src/test/xml/batchtestreordering-artifacts.xml");
    String expectedReply = FileUtils.readFileToString(expectedResultFile);

    URI uri = new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/batch/retrieve");

    // Note: need PushbackInputStream to prevent the call to getBody() being made more than once.
    // See MessageBodyClientHttpResponseWrapper.

    InputStream responseStream = new PushbackInputStream(new ByteArrayInputStream(expectedReply.getBytes()));

    HttpHeaders headers = new HttpHeaders();

    ClientHttpResponse httpResponse = EasyMock.createMock(ClientHttpResponse.class);
    EasyMock.expect(httpResponse.getStatusCode()).andReturn(HttpStatus.OK).anyTimes();
    EasyMock.expect(httpResponse.getRawStatusCode()).andReturn(HttpStatus.OK.value()).anyTimes();
    EasyMock.expect(httpResponse.getHeaders()).andReturn(headers).anyTimes();
    EasyMock.expect(httpResponse.getBody()).andReturn(responseStream).once();
    httpResponse.close();//from   w w  w .jav a 2  s .c o  m
    EasyMock.expectLastCall().once();

    ClientHttpRequest httpRequest = EasyMock.createMock(ClientHttpRequest.class);
    EasyMock.expect(httpRequest.getHeaders()).andReturn(headers).anyTimes();
    EasyMock.expect(httpRequest.getBody()).andReturn(new NullOutputStream()).times(0, 2);
    EasyMock.expect(httpRequest.execute()).andReturn(httpResponse).once();

    ClientHttpRequestFactory mockFactory = EasyMock.createStrictMock(ClientHttpRequestFactory.class);
    EasyMock.expect(mockFactory.createRequest(uri, HttpMethod.POST)).andReturn(httpRequest).once();

    restTemplate.setRequestFactory(mockFactory);

    EasyMock.replay(httpResponse, httpRequest, mockFactory);

    List<Artifact> artifacts = api.loadAll(links);

    assertEquals("Wrong number of artifacts", links.size(), artifacts.size());

    for (int i = 0; i < links.size(); i++) {
        assertTrue("Artifact " + i + " wrong: " + artifacts.get(i).getUri(),
                artifacts.get(i).getUri().toString().startsWith(links.get(i).getUri().toString()));
    }

    EasyMock.verify(httpResponse, httpRequest, mockFactory);
}

From source file:org.cruk.genologics.api.GenologicsAPIBatchOperationTest.java

@Test
public void testArtifactBatchUpdate() throws Exception {
    File expectedResultFile = new File("src/test/xml/batchtestreordering-artifacts.xml");
    String expectedReply = FileUtils.readFileToString(expectedResultFile);

    ArtifactBatchFetchResult updateArtifactsFetch = (ArtifactBatchFetchResult) marshaller
            .unmarshal(new StreamSource(expectedResultFile));

    List<Artifact> artifacts = updateArtifactsFetch.getArtifacts();

    // Rearrange these to a different order to that in the file.
    // This means the original XML file loaded above will return in an order
    // not matching either the Links object (below) or the original order
    // of the artifacts.
    Collections.shuffle(artifacts, new Random(997));

    // Copy the URI order as it is now to make sure it doesn't differ
    // after updating the artifacts.
    List<URI> uriOrder = new ArrayList<URI>();

    Links confirmLinks = new Links();
    for (Artifact a : artifacts) {
        uriOrder.add(a.getUri());/*from w w  w .  j av a 2 s . com*/
        confirmLinks.getLinks().add(new Link(a));
    }

    // The Links object that (would) come back should be in a different order.
    Collections.shuffle(confirmLinks.getLinks(), new Random(1024));

    StringWriter linksXML = new StringWriter();
    marshaller.marshal(confirmLinks, new StreamResult(linksXML));

    // Two calls to make here.

    URI updateUri = new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/batch/update");
    URI retrieveUri = new URI("http://limsdev.cri.camres.org:8080/api/v2/artifacts/batch/retrieve");

    // Note: need PushbackInputStream to prevent the call to getBody() being made more than once.
    // See MessageBodyClientHttpResponseWrapper.

    InputStream response1Stream = new PushbackInputStream(
            new ByteArrayInputStream(linksXML.toString().getBytes()));
    InputStream response2Stream = new PushbackInputStream(new ByteArrayInputStream(expectedReply.getBytes()));

    HttpHeaders headers = new HttpHeaders();

    ClientHttpResponse httpResponse1 = EasyMock.createMock(ClientHttpResponse.class);
    EasyMock.expect(httpResponse1.getStatusCode()).andReturn(HttpStatus.OK).anyTimes();
    EasyMock.expect(httpResponse1.getRawStatusCode()).andReturn(HttpStatus.OK.value()).anyTimes();
    EasyMock.expect(httpResponse1.getHeaders()).andReturn(headers).anyTimes();
    EasyMock.expect(httpResponse1.getBody()).andReturn(response1Stream).once();
    httpResponse1.close();
    EasyMock.expectLastCall().once();

    ClientHttpRequest httpRequest1 = EasyMock.createMock(ClientHttpRequest.class);
    EasyMock.expect(httpRequest1.getHeaders()).andReturn(headers).anyTimes();
    EasyMock.expect(httpRequest1.getBody()).andReturn(new NullOutputStream()).times(0, 2);
    EasyMock.expect(httpRequest1.execute()).andReturn(httpResponse1).once();

    ClientHttpResponse httpResponse2 = EasyMock.createMock(ClientHttpResponse.class);
    EasyMock.expect(httpResponse2.getStatusCode()).andReturn(HttpStatus.OK).anyTimes();
    EasyMock.expect(httpResponse2.getRawStatusCode()).andReturn(HttpStatus.OK.value()).anyTimes();
    EasyMock.expect(httpResponse2.getHeaders()).andReturn(headers).anyTimes();
    EasyMock.expect(httpResponse2.getBody()).andReturn(response2Stream).once();
    httpResponse2.close();
    EasyMock.expectLastCall().once();

    ClientHttpRequest httpRequest2 = EasyMock.createMock(ClientHttpRequest.class);
    EasyMock.expect(httpRequest2.getHeaders()).andReturn(headers).anyTimes();
    EasyMock.expect(httpRequest2.getBody()).andReturn(new NullOutputStream()).times(0, 2);
    EasyMock.expect(httpRequest2.execute()).andReturn(httpResponse2).once();

    ClientHttpRequestFactory mockFactory = EasyMock.createStrictMock(ClientHttpRequestFactory.class);
    EasyMock.expect(mockFactory.createRequest(updateUri, HttpMethod.POST)).andReturn(httpRequest1).once();
    EasyMock.expect(mockFactory.createRequest(retrieveUri, HttpMethod.POST)).andReturn(httpRequest2).once();

    restTemplate.setRequestFactory(mockFactory);

    EasyMock.replay(httpResponse1, httpRequest1, httpResponse2, httpRequest2, mockFactory);

    api.updateAll(artifacts);

    assertEquals("Wrong number of artifacts", uriOrder.size(), artifacts.size());

    for (int i = 0; i < uriOrder.size(); i++) {
        assertEquals("Artifact " + i + " wrong:", uriOrder.get(i), artifacts.get(i).getUri());
    }

    EasyMock.verify(httpResponse2, httpRequest2, mockFactory);
}

From source file:org.fao.geonet.doi.client.DoiClient.java

private String retrieve(String url, String entity) throws DoiClientException {

    ClientHttpResponse httpResponse = null;
    HttpGet getMethod = null;/*from w w w.j a  va 2 s. c o  m*/

    try {
        Log.debug(LOGGER_NAME, "   -- URL: " + url);

        getMethod = new HttpGet(url);

        httpResponse = requestFactory.execute(getMethod, new UsernamePasswordCredentials(username, password),
                AuthScope.ANY);
        int status = httpResponse.getRawStatusCode();

        Log.debug(LOGGER_NAME, "   -- Request status code: " + status);

        if (status == HttpStatus.SC_OK) {
            return CharStreams.toString(new InputStreamReader(httpResponse.getBody()));
        } else if (status == HttpStatus.SC_NO_CONTENT) {
            return null; // Not found
        } else if (status == HttpStatus.SC_NOT_FOUND) {
            return null; // Not found
        } else {
            Log.info(LOGGER_NAME, "Retrieve DOI metadata end -- Error: " + httpResponse.getStatusText());

            throw new DoiClientException(httpResponse.getStatusText()
                    + CharStreams.toString(new InputStreamReader(httpResponse.getBody())));
        }

    } catch (Exception ex) {
        Log.error(LOGGER_NAME, "   -- Error (exception): " + ex.getMessage());
        throw new DoiClientException(ex.getMessage());

    } finally {
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
        // Release the connection.
        IOUtils.closeQuietly(httpResponse);
    }
}

From source file:org.jboss.windup.decorator.integration.mvn.MavenCentralSHA1VersionDecorator.java

@Override
public void processMeta(ZipMetadata meta) {
    if (!active) {
        return;//from w ww.  j a  v a  2 s .  com
    }
    if (!knownArchiveProfiler.isExclusivelyKnownArchive(meta)) {
        return;
    }

    String sha1Hash = null;
    for (AbstractDecoration result : meta.getDecorations()) {
        if (result instanceof PomVersion) {
            LOG.debug("Already has version result: " + result.toString());
            return;
        } else if (result instanceof Hash) {
            if (((Hash) result).getHashType() == HashType.SHA1) {
                sha1Hash = ((Hash) result).getHash();
            }
        }
    }

    if (sha1Hash == null) {
        LOG.debug("No SHA-1 Hash found. Returning.");
        return;
    }
    LOG.info("No Version Found: " + meta.getRelativePath() + "; trying Maven Central");
    if (LOG.isDebugEnabled()) {
        LOG.debug("SHA1: " + sha1Hash);
    }
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

    try {
        MavenCentralSHA1VersionResponseWrapper result = restTemplate.getForObject(MAVEN_API_URL,
                MavenCentralSHA1VersionResponseWrapper.class, sha1Hash);

        if (result != null && result.getResponse() != null && result.getResponse().getNumFound() > 0) {
            MavenCentralSHA1VersionResponseItem rsp = result.getResponse().getDocs()[0];
            String groupId = rsp.getGroupId();
            String artifactId = rsp.getArtifactId();
            String version = rsp.getVersion();

            String url = generateUrl(groupId, artifactId, version);

            // pull the POM from the URL.
            ClientHttpRequestFactory request = new SimpleClientHttpRequestFactory();
            try {
                ClientHttpRequest pomRequest = request.createRequest(new URI(url), HttpMethod.GET);
                ClientHttpResponse resp = pomRequest.execute();

                String outputDir = meta.getArchiveOutputDirectory().getAbsolutePath() + File.separator
                        + "maven-remote";
                FileUtils.forceMkdir(new File(outputDir));

                File outputPath = new File(outputDir + File.separator + "pom.xml");
                IOUtils.copy(new InputStreamReader(resp.getBody()), new FileOutputStream(outputPath));

                XmlMetadata xmlMeta = new XmlMetadata();
                xmlMeta.setFilePointer(outputPath);
                xmlMeta.setArchiveMeta(meta);

                pomInterrogator.processMeta(xmlMeta);
                LOG.info("Fetched remote POM for: " + meta.getName());
            } catch (Exception e) {
                LOG.error("Exception fetching remote POM: " + url + "; skipping.", e);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No Version Information Found in Maven Central for: " + sha1Hash);
            }
        }
    } catch (Exception e) {
        LOG.error("Exception creating API call to Central Repo for POM: " + meta.getName() + "; skipping.", e);
    }
}

From source file:org.openflamingo.collector.handler.HttpToLocalHandler.java

/**
 * HTTP  URL? ./*w  w  w .ja  va2s  .  c o  m*/
 *
 * @param http HTTP
 * @return HTTP Response String
 * @throws Exception HTTP ? ?? ? ? 
 */
private String getResponse(FromHttp http) throws Exception {
    logger.info("HTTP URL?    ?  .");

    String url = jobContext.getValue(http.getUrl().trim());
    String method = jobContext.getValue(http.getMethod().getType());

    logger.info("HTTP URL Information :");
    logger.info("   URL = {}", url);
    logger.info("   Method = {}", method);

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    ClientHttpRequest request = null;
    if ("POST".equals(method)) {
        request = factory.createRequest(new java.net.URI(url), POST);
    } else {
        request = factory.createRequest(new java.net.URI(url), GET);
    }

    if (http.getHeaders() != null && http.getHeaders().getHeader().size() > 0) {
        List<Header> header = http.getHeaders().getHeader();
        logger.info("HTTP Header :", new String[] {});
        for (Header h : header) {
            String name = h.getName();
            String value = jobContext.getValue(h.getValue());
            request.getHeaders().add(name, value);
            logger.info("\t{} = {}", name, value);
        }
    }

    String responseBodyAsString = null;
    ClientHttpResponse response = null;
    try {
        response = request.execute();
        responseBodyAsString = new String(FileCopyUtils.copyToByteArray(response.getBody()),
                Charset.defaultCharset());
        logger.debug("HTTP ? ?  ? .\n{}", responseBodyAsString);
        logger.info("HTTP ? . ?  '{}({})'.",
                response.getStatusText(), response.getRawStatusCode());
        if (response.getRawStatusCode() != HttpStatus.OK.value()) {
            throw new SystemException(ExceptionUtils.getMessage(
                    "HTTP URL ? . ? OK  '{}({})'  ? .",
                    response.getStatusText(), response.getRawStatusCode()));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new SystemException(
                ExceptionUtils.getMessage("HTTP URL ? . ? : {}",
                        ExceptionUtils.getRootCause(ex).getMessage()),
                ex);
    } finally {
        try {
            response.close();
        } catch (Exception ex) {
            // Ignored
        }
    }
    return responseBodyAsString;
}

From source file:org.opentestsystem.shared.trapi.exception.TrApiResponseErrorHandler.java

public void handleError(ClientHttpResponse response) throws IOException {
    String responseString = IOUtils.toString(response.getBody());
    try {//  w  ww  .  ja  v a 2  s  .com
        ResponseMessage message = JsonHelper.deserialize(responseString, ResponseMessage.class);
        responseString = message.getMessages();
    } catch (Exception ex) {
        //not all response are of message type hence use original string
    }
    String statusCode = response.getStatusCode().name();
    if (response.getStatusCode() == HttpStatus.NOT_IMPLEMENTED) {
        if (TrApiErrorCode.LOCAL_OK.getCode().equals(responseString)) {
            statusCode = responseString;
        }
    }
    TrApiException exception = new TrApiException(statusCode, responseString);
    throw exception;
}