List of usage examples for org.springframework.http.client ClientHttpResponse getStatusCode
HttpStatus getStatusCode() throws IOException;
From source file:org.cloudfoundry.identity.api.web.ServerRunning.java
public HttpStatus getStatusCode(String path, final HttpHeaders headers) { RequestCallback requestCallback = new NullRequestCallback(); if (headers != null) { requestCallback = new RequestCallback() { @Override// ww w .ja v a2 s .co m public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().putAll(headers); } }; } return client.execute(getUrl(path), HttpMethod.GET, requestCallback, new ResponseExtractor<ResponseEntity<String>>() { @Override public ResponseEntity<String> extractData(ClientHttpResponse response) throws IOException { return new ResponseEntity<String>(response.getStatusCode()); } }).getStatusCode(); }
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 ww. java 2 s . co 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());//ww w. ja v a2 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.opentestsystem.shared.trapi.exception.TrApiResponseErrorHandler.java
public void handleError(ClientHttpResponse response) throws IOException { String responseString = IOUtils.toString(response.getBody()); try {/*from www . ja v a2s . c o m*/ 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; }
From source file:org.springframework.boot.devtools.remote.client.ClassPathChangeUploader.java
@Override public void onApplicationEvent(ClassPathChangedEvent event) { try {/*w w w .jav a2s . c o m*/ ClassLoaderFiles classLoaderFiles = getClassLoaderFiles(event); ClientHttpRequest request = this.requestFactory.createRequest(this.uri, HttpMethod.POST); byte[] bytes = serialize(classLoaderFiles); HttpHeaders headers = request.getHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentLength(bytes.length); FileCopyUtils.copy(bytes, request.getBody()); logUpload(classLoaderFiles); ClientHttpResponse response = request.execute(); Assert.state(response.getStatusCode() == HttpStatus.OK, "Unexpected " + response.getStatusCode() + " response uploading class files"); } catch (IOException ex) { throw new IllegalStateException(ex); } }
From source file:org.springframework.boot.devtools.remote.client.DelayedLiveReloadTrigger.java
private boolean isUp() { try {/* ww w . ja v a 2 s. c o m*/ ClientHttpRequest request = createRequest(); ClientHttpResponse response = request.execute(); return response.getStatusCode() == HttpStatus.OK; } catch (Exception ex) { return false; } }
From source file:org.springframework.cloud.netflix.turbine.stream.TurbineStreamTests.java
private ResponseEntity<String> extract(ClientHttpResponse response) throws IOException { // The message has to be sent after the endpoint is activated, so this is a // convenient place to put it stubTrigger.trigger("metrics"); byte[] bytes = new byte[1024]; StringBuilder builder = new StringBuilder(); int read = 0; while (read >= 0 && StringUtils.countOccurrencesOf(builder.toString(), "\n") < 2) { read = response.getBody().read(bytes, 0, bytes.length); if (read > 0) { latch.countDown();/* www . j a v a 2s. c o m*/ builder.append(new String(bytes, 0, read)); } log.debug("Building: " + builder); } log.debug("Done: " + builder); return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()) .body(builder.toString()); }
From source file:org.springframework.data.document.couchdb.core.AbstractCouchTemplateIntegrationTests.java
@Before public void setUpTestDatabase() throws Exception { RestTemplate template = new RestTemplate(); template.setErrorHandler(new DefaultResponseErrorHandler() { @Override//from w w w.ja v a 2 s . com public void handleError(ClientHttpResponse response) throws IOException { // do nothing, error status will be handled in the switch statement } }); ResponseEntity<String> response = template.getForEntity(CouchConstants.TEST_DATABASE_URL, String.class); HttpStatus statusCode = response.getStatusCode(); switch (statusCode) { case NOT_FOUND: createNewTestDatabase(); break; case OK: deleteExisitingTestDatabase(); createNewTestDatabase(); break; default: throw new IllegalStateException("Unsupported http status [" + statusCode + "]"); } }
From source file:org.springframework.web.client.interceptors.ZeroLeggedOAuthInterceptorTest.java
@Test public void testInterceptor() throws Exception { final String url = "http://www.test.com/lrs?param1=val1¶m2=val2"; final String data = "test"; final String id = "test"; final String realm = "realm"; final String consumerKey = "consumerKey"; final String secretKey = "secretKey"; PropertyResolver resolver = mock(PropertyResolver.class); when(resolver.getProperty(eq("org.jasig.rest.interceptor.oauth." + id + ".realm"))).thenReturn(realm); when(resolver.getProperty(eq("org.jasig.rest.interceptor.oauth." + id + ".consumerKey"))) .thenReturn(consumerKey);/*from w ww .j a v a2s . c om*/ when(resolver.getProperty(eq("org.jasig.rest.interceptor.oauth." + id + ".secretKey"))) .thenReturn(secretKey); // holder for the headers... HttpHeaders headers = new HttpHeaders(); // Mock guts of RestTemplate so no need to actually hit the web... ClientHttpResponse resp = mock(ClientHttpResponse.class); when(resp.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); when(resp.getHeaders()).thenReturn(new HttpHeaders()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ClientHttpRequest client = mock(ClientHttpRequest.class); when(client.getHeaders()).thenReturn(headers); when(client.getBody()).thenReturn(buffer); when(client.execute()).thenReturn(resp); ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class); when(factory.createRequest(any(URI.class), any(HttpMethod.class))).thenReturn(client); // add the new interceptor... ZeroLeggedOAuthInterceptor interceptor = new ZeroLeggedOAuthInterceptor(); interceptor.setPropertyResolver(resolver); interceptor.setId(id); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(interceptor); RestTemplate rest = new RestTemplate(factory); rest.setInterceptors(interceptors); rest.postForLocation(url, data, Collections.emptyMap()); // make sure auth header is correctly set... assertThat(headers, hasKey(Headers.Authorization.name())); String authHeader = headers.get(Headers.Authorization.name()).get(0); assertThat(authHeader, containsString("OAuth realm=\"" + realm + "\"")); assertThat(authHeader, containsString("oauth_consumer_key=\"" + consumerKey + "\"")); // for now, only supports HMAC-SHA1. May have to fix later... assertThat(authHeader, containsString("oauth_signature_method=\"HMAC-SHA1\"")); assertThat(authHeader, containsString("oauth_version=\"1.0\"")); assertThat(authHeader, containsString("oauth_timestamp=")); assertThat(authHeader, containsString("oauth_nonce=")); assertThat(authHeader, containsString("oauth_signature=")); // oauth lib will create 2 oauth_signature params if you call sign // multiple times. Make sure only get 1. assertThat(StringUtils.countMatches(authHeader, "oauth_signature="), is(1)); }