List of usage examples for org.springframework.http.client ClientHttpResponse getRawStatusCode
int getRawStatusCode() throws IOException;
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithProtobuf() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {/*from www .j a v a 2 s.co m*/ context.refresh(); final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class); RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); error = httpClient.postForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/headerRequired"), null, ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithJson() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("websocket.enabled", "false"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {/*from ww w . j a va 2 s . c o m*/ context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithJsonWithHTTPS() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("https.enabled", "true"); properties.put("https.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("https.hostname", "localhost"); properties.put("https.selfSigned", "true"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {/*from w w w . j a v a 2s. c o m*/ context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build()); RestTemplate httpClient = new RestTemplate(requestFactory); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("https.enabled", "true"); properties.put("https.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("https.hostname", "localhost"); properties.put("https.selfSigned", "true"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {//from w w w . j a v a2s .c o m context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build()); RestTemplate httpClient = new RestTemplate(requestFactory); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:io.github.microcks.util.test.HttpTestRunner.java
@Override public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult, List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException { if (log.isDebugEnabled()) { log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)"); }//from ww w.j a v a 2 s.c o m // Initialize result container. List<TestReturn> result = new ArrayList<TestReturn>(); for (Request request : requests) { // Reset status code, message and request each time. int code = TestReturn.SUCCESS_CODE; String message = null; String customizedEndpointUrl = endpointUrl; if (service.getType().equals(ServiceType.REST)) { String operationName = operation.getName(); // Name may start with verb, remove it if present. if (operationName.indexOf(' ') > 0 && operationName.indexOf(' ') < operationName.length()) { operationName = operationName.split(" ")[1]; } customizedEndpointUrl += URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters()); log.debug("Using customized endpoint url: " + customizedEndpointUrl); } ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(new URI(customizedEndpointUrl), method); // Set headers to request if any. Set<Header> headers = request.getHeaders(); if (headers != null && headers.size() > 0) { for (Header header : headers) { httpRequest.getHeaders().add(header.getName(), buildValue(header.getValues())); } } // If there's input content, add it to request. if (request.getContent() != null) { httpRequest.getBody().write(request.getContent().getBytes()); } // Actually execute request. long startTime = System.currentTimeMillis(); ClientHttpResponse httpResponse = null; try { httpResponse = httpRequest.execute(); } catch (IOException ioe) { log.error("IOException while executing request " + request.getName() + " on " + endpointUrl, ioe); code = TestReturn.FAILURE_CODE; message = ioe.getMessage(); } long duration = System.currentTimeMillis() - startTime; // Extract and store response body so that stream may not be consumed more than o1 time ;-) String responseContent = null; if (httpResponse != null) { StringWriter writer = new StringWriter(); IOUtils.copy(httpResponse.getBody(), writer); responseContent = writer.toString(); } // If still in success, check if http code is out of correct ranges (20x and 30x). if (code == TestReturn.SUCCESS_CODE) { code = extractTestReturnCode(service, operation, request, httpResponse, responseContent); message = extractTestReturnMessage(service, operation, request, httpResponse); } // Create a Response object for returning. Response response = new Response(); if (httpResponse != null) { response.setContent(responseContent); response.setStatus(String.valueOf(httpResponse.getRawStatusCode())); response.setMediaType(httpResponse.getHeaders().getContentType().toString()); headers = buildHeaders(httpResponse); if (headers != null) { response.setHeaders(headers); } } result.add(new TestReturn(code, duration, message, request, response)); } return result; }
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 {//from w w w . j av a 2s. c o 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.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 www. ja v a2s . 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());// w ww . j av a2s . co 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.doi.client.DoiClient.java
/** * This request marks a dataset as 'inactive'. * To activate it again, POST new metadata or set the isActive-flag in the user interface. * * @param doi//from w w w . j ava2 s. co m * @throws DoiClientException */ public void deleteDoiMetadata(String doi) throws DoiClientException { ClientHttpResponse httpResponse = null; HttpDelete deleteMethod = null; try { Log.debug(LOGGER_NAME, " -- URL: " + this.serverUrl + "/metadata"); deleteMethod = new HttpDelete(createUrl("metadata/" + doi)); httpResponse = requestFactory.execute(deleteMethod, new UsernamePasswordCredentials(username, password), AuthScope.ANY); int status = httpResponse.getRawStatusCode(); Log.debug(LOGGER_NAME, " -- Request status code: " + status); // Ignore NOT FOUND (trying to delete a non existing doi metadata) if ((status != HttpStatus.SC_NOT_FOUND) && (status != HttpStatus.SC_OK)) { Log.info(LOGGER_NAME, "Delete DOI metadata end -- Error: " + httpResponse.getStatusText()); throw new DoiClientException(httpResponse.getStatusText()); } else { Log.info(LOGGER_NAME, "DeleteDOI metadata end"); } } catch (Exception ex) { Log.error(LOGGER_NAME, " -- Error (exception): " + ex.getMessage()); throw new DoiClientException(ex.getMessage()); } finally { if (deleteMethod != null) { deleteMethod.releaseConnection(); } // Release the connection. IOUtils.closeQuietly(httpResponse); } }