List of usage examples for org.springframework.web.client RestTemplate setInterceptors
public void setInterceptors(List<ClientHttpRequestInterceptor> interceptors)
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 ww w. j av a2 s . c om*/ 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 {// w w w .j a v a 2 s . co 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:org.springframework.boot.test.web.client.TestRestTemplate.java
private void addAuthentication(RestTemplate restTemplate, String username, String password) { if (username == null) { return;//from w ww . ja v a 2 s . c o m } List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); if (interceptors == null) { interceptors = Collections.emptyList(); } interceptors = new ArrayList<>(interceptors); Iterator<ClientHttpRequestInterceptor> iterator = interceptors.iterator(); while (iterator.hasNext()) { if (iterator.next() instanceof BasicAuthorizationInterceptor) { iterator.remove(); } } interceptors.add(new BasicAuthorizationInterceptor(username, password)); restTemplate.setInterceptors(interceptors); }
From source file:org.cloudfoundry.identity.uaa.api.common.impl.UaaConnectionHelper.java
/** * Make a REST call with custom headers//ww w. j a v a2 s . c om * * @param method the Http Method (GET, POST, etc) * @param uri the URI of the endpoint (relative to the base URL set in the constructor) * @param body the request body * @param responseType the object type to be returned * @param uriVariables any uri variables * @return the response body * @see org.springframework.web.client.RestTemplate#exchange(String, HttpMethod, HttpEntity, ParameterizedTypeReference, Object...) */ private <RequestType, ResponseType> ResponseType exchange(HttpMethod method, HttpHeaders headers, RequestType body, String uri, ParameterizedTypeReference<ResponseType> responseType, Object... uriVariables) { getHeaders(headers); RestTemplate template = new RestTemplate(); template.setInterceptors(LoggerInterceptor.INTERCEPTOR); HttpEntity<RequestType> requestEntity = null; if (body == null) { requestEntity = new HttpEntity<RequestType>(headers); } else { requestEntity = new HttpEntity<RequestType>(body, headers); } // combine url into the varargs List<Object> varList = new ArrayList<Object>(); varList.add(url); if (uriVariables != null && uriVariables.length > 0) { varList.addAll(Arrays.asList(uriVariables)); } ResponseEntity<ResponseType> responseEntity = template.exchange("{base}" + uri, method, requestEntity, responseType, varList.toArray()); if (HttpStatus.Series.SUCCESSFUL.equals(responseEntity.getStatusCode().series())) { return responseEntity.getBody(); } else { return null; } }
From source file:org.springframework.cloud.config.client.ConfigServicePropertySourceLocator.java
private RestTemplate getSecureRestTemplate(ConfigClientProperties client) { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setReadTimeout((60 * 1000 * 3) + 5000); //TODO 3m5s, make configurable? RestTemplate template = new RestTemplate(requestFactory); String password = client.getPassword(); if (password != null) { template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList( new BasicAuthorizationInterceptor(client.getUsername(), password))); }/*w ww .j av a 2 s . c om*/ return template; }
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);/* w ww .jav a 2s .c o m*/ 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)); }