List of usage examples for org.springframework.http.client ClientHttpResponse close
@Override
void close();
From source file:org.springframework.web.client.RestTemplate.java
/** * Execute the given method on the provided URI. * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback}; * the response with the {@link ResponseExtractor}. * @param url the fully-expanded URL to connect to * @param method the HTTP method to execute (GET, POST, etc.) * @param requestCallback object that prepares the request (can be {@code null}) * @param responseExtractor object that extracts the return value from the response (can be {@code null}) * @return an arbitrary object, as returned by the {@link ResponseExtractor} *//* www . jav a2 s.c o m*/ protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "'url' must not be null"); Assert.notNull(method, "'method' must not be null"); ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); if (!getErrorHandler().hasError(response)) { logResponseStatus(method, url, response); } else { handleResponseError(method, url, response); } if (responseExtractor != null) { return responseExtractor.extractData(response); } else { return null; } } catch (IOException ex) { throw new ResourceAccessException( "I/O error on " + method.name() + " request for \"" + url + "\": " + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } }
From source file:com.jaspersoft.android.sdk.client.JsRestClient.java
private void downloadFile(URI uri, File file) throws RestClientException { ClientHttpResponse response = null; try {// w w w .j a va2 s .c o m ClientHttpRequest request = restTemplate.getRequestFactory().createRequest(uri, HttpMethod.GET); response = request.execute(); if (restTemplate.getErrorHandler().hasError(response)) { restTemplate.getErrorHandler().handleError(response); } copyResponseToFile(response, file); } catch (IOException ex) { throw new ResourceAccessException("I/O error: " + ex.getMessage(), ex); } finally { if (response != null) response.close(); } }
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(); EasyMock.expectLastCall().once();/*from w ww . j a v a 2 s . c o m*/ 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 ww w. jav a2 s . c o m*/ 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.monitor.health.DashboardAppHealthCheck.java
public HealthCheck create(final ServiceContext context) { return new HealthCheck(this.getClass().getSimpleName()) { @Override//ww w .j a v a 2 s . com protected Result check() throws Exception { final GeonetHttpRequestFactory httpRequestFactory = context.getBean(GeonetHttpRequestFactory.class); final SettingManager settingManager = context.getBean(SettingManager.class); final EsSearchManager searchMan = context.getBean(EsSearchManager.class); final String dashboardAppUrl = searchMan.getClient().getDashboardAppUrl(); if (StringUtils.isNotEmpty(dashboardAppUrl)) { ClientHttpResponse httpResponse = null; try { String url = settingManager.getBaseURL() + "dashboards/api/status"; httpResponse = httpRequestFactory.execute(new HttpGet(url)); if (httpResponse.getRawStatusCode() == 200) { return Result.healthy(String.format("Dashboard application is running.")); } else { return Result.unhealthy("Dashboard application is not available currently. " + "This component is only required if you use dashboards."); } } catch (Throwable e) { return Result.unhealthy(e); } finally { if (httpResponse != null) { httpResponse.close(); } } } else { return Result.unhealthy("Dashboard application is not configured. " + "Update config.properties to setup Kibana to use this feature."); } } }; }
From source file:org.openflamingo.collector.handler.HttpToLocalHandler.java
/** * HTTP URL? ./*from w ww. j a va2s . co 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.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactoryTests.java
@Test public void mimeType() throws Exception { FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.xxcss"))); AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setDocumentRoot(this.temporaryFolder.getRoot()); MimeMappings mimeMappings = new MimeMappings(); mimeMappings.add("xxcss", "text/css"); factory.setMimeMappings(mimeMappings); this.container = factory.getEmbeddedServletContainer(); this.container.start(); ClientHttpResponse response = getClientResponse("http://localhost:8080/test.xxcss"); assertThat(response.getHeaders().getContentType().toString(), equalTo("text/css")); response.close(); }
From source file:org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactoryTests.java
protected String getResponse(String url) throws IOException, URISyntaxException { ClientHttpResponse response = getClientResponse(url); try {/*from w ww.java 2s .c o m*/ return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); } finally { response.close(); } }