List of usage examples for org.springframework.web.client RestTemplate setInterceptors
public void setInterceptors(List<ClientHttpRequestInterceptor> interceptors)
From source file:com.kixeye.chassis.transport.shared.SharedTest.java
@Test public void testSwagger() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.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(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try {//from w ww. j a va2 s. c om context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/swagger/index.html"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().contains("<title>Swagger UI</title>")); } finally { context.close(); } }
From source file:com.kixeye.chassis.transport.shared.SharedTest.java
@Test public void testAdminLinks() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.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(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try {//from w ww. j ava 2 s . com context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity( new URI("http://localhost:" + properties.get("admin.port") + "/admin/index.html"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/ping\">Ping</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/healthcheck\">Healthcheck</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/metrics?pretty=true\">Metrics</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/admin/properties\">Properties</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/threads\">Threads</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/admin/classpath\">Classpath</a>")); } finally { context.close(); } }
From source file:net.bull.javamelody.SpringRestTemplateBeanPostProcessor.java
/** {@inheritDoc} */ @Override//from w ww . j a va2 s.c o m public Object postProcessAfterInitialization(Object bean, String beanName) { // RestTemplate et getInterceptors() existent depuis spring-web 3.1.0.RELEASE if (REST_TEMPLATE_INTERCEPTOR_AVAILABLE && bean instanceof RestTemplate) { final RestTemplate restTemplate = (RestTemplate) bean; final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>( restTemplate.getInterceptors()); for (final ClientHttpRequestInterceptor interceptor : interceptors) { if (interceptor instanceof SpringRestTemplateInterceptor) { return bean; } } interceptors.add(SpringRestTemplateInterceptor.SINGLETON); restTemplate.setInterceptors(interceptors); } return bean; }
From source file:com.epl.ticketws.services.QueryService.java
public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) { try {//from w w w. j a v a 2 s.com URI uri = new URL(url).toURI(); long timestamp = new Date().getTime(); HttpMethod httpMethod; if (method.equalsIgnoreCase("post")) { httpMethod = HttpMethod.POST; } else { httpMethod = HttpMethod.GET; } String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters); // logger.info("String to sign: " + stringToSign); String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license); // logger.info("Authorization string: " + authorization); // Setting Headers HttpHeaders headers = new HttpHeaders(); if (accept.equalsIgnoreCase("json")) { headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); } else { headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); } headers.add("Authorization", authorization); headers.add("OB_DATE", "" + timestamp); headers.add("OB_Terminal", terminal); headers.add("OB_User", user); headers.add("OB_Channel", channel); headers.add("OB_POS", pos); headers.add("Content-Type", "application/x-www-form-urlencoded"); HttpEntity<String> entity; if (httpMethod == HttpMethod.POST) { // Adding post parameters to POST body String parameterStringBody = getParametersAsString(parameters); entity = new HttpEntity<String>(parameterStringBody, headers); // logger.info("POST Body: " + parameterStringBody); } else { entity = new HttpEntity<String>(headers); } RestTemplate restTemplate = new RestTemplate( new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new LoggingRequestInterceptor()); restTemplate.setInterceptors(interceptors); // Converting to UTF-8. OB Rest replies in windows charset. //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(UTF_8))); if (accept.equalsIgnoreCase("json")) { restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter()); } else { restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter()); } ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc); if (!response.getStatusCode().is2xxSuccessful()) throw new HttpClientErrorException(response.getStatusCode()); return response.getBody(); } catch (HttpClientErrorException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (MalformedURLException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (SignatureException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return null; }
From source file:com.pepaproch.gtswsdlclient.AddresCheckImplTest.java
/** * Test of checkAddres method, of class AddresCheckImpl. */// w ww. j av a2s.com @Test public void testCheckAddresAuthenticated() { System.out.println("checkAddres"); AddressQuery addrQuery = new AddressQuery(); RestTemplate restTemplate = getRestTemplate(); RestTemplate authRestTemplate = getRestTemplate(); AuthTokenProviderImpl authTokenProvider = new AuthTokenProviderImpl(BASE_URL, "test", "test", authRestTemplate, 1); AuthHeaderInterceptor securityTokenInterceptor = new AuthHeaderInterceptor(authTokenProvider); List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); if (interceptors == null) { interceptors = new ArrayList<>(); restTemplate.setInterceptors(interceptors); } interceptors.add(securityTokenInterceptor); RestContext restContext = Mockito.mock(RestContext.class); when(restContext.getRestTemplate()).thenReturn(restTemplate); when(restContext.getBASE_URL()).thenReturn(BASE_URL); //first request AddressResponse expResult = null; mockServer = MockRestServiceServer.createServer(restTemplate); this.mockServer.expect(requestTo(BASE_URL + AddresCheckImpl.ADDR_CHECK_PATH)) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(CHECK_ADDR_RESPONSE_BODY, MediaType.APPLICATION_JSON)); //auth token is not set so it will call remote for acces token mockServerAuthProvider = MockRestServiceServer.createServer(authRestTemplate); String authResponseBody = "{\"accessToken\" : \"testtoken\" }"; mockServerAuthProvider.expect(requestTo(BASE_URL + AUTH_PATH)).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(authResponseBody, MediaType.APPLICATION_JSON)); //token is set with no valid time so token should be renewed String authResponseBody1 = "{\"accessToken\" : \"testtoken-1\" }"; mockServerAuthProvider.expect(requestTo(BASE_URL + AUTH_PATH)).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(authResponseBody1, MediaType.APPLICATION_JSON)); //second call with no valid auth token this.mockServer.expect(requestTo(BASE_URL + AddresCheckImpl.ADDR_CHECK_PATH)) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(CHECK_ADDR_RESPONSE_BODY, MediaType.APPLICATION_JSON)); AddresCheckImpl instance = new AddresCheckImpl(restContext); AddressResponse result = instance.checkAddres(addrQuery); String authToken1 = authTokenProvider.getAuthorisationToken().toString(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } AddressResponse result1 = instance.checkAddres(addrQuery); String authToken2 = authTokenProvider.getAuthorisationToken().toString(); Integer expectedTotal = new Integer(3); assertEquals(result.getTotal(), expectedTotal); mockServer.verify(); mockServerAuthProvider.verify(); }
From source file:com.kixeye.chassis.transport.HybridServiceTest.java
@Test public void testHybridService() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.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(TestCombinedService.class); WebSocketClient wsClient = new WebSocketClient(); RestTemplate httpClient = new RestTemplate(); try {//from www .ja va 2s .c o m context.refresh(); final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null); Session session = wsClient .connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/protobuf")) .get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); 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("more stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("even more 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("even more stuff", response.value); } finally { try { wsClient.stop(); } finally { context.close(); } } }
From source file:com.netflix.genie.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * Constructor./*from ww w . j av a2 s . c om*/ * * @param serverProperties The properties of the resource server (Genie) * @param converter The access token converter to use * @param registry The metrics registry to use */ public PingFederateRemoteTokenServices(@NotNull final ResourceServerProperties serverProperties, @NotNull final AccessTokenConverter converter, @NotNull final MeterRegistry registry) { super(); this.authenticationTimer = registry.timer(AUTHENTICATION_TIMER_NAME); this.pingFederateAPITimer = registry.timer(API_TIMER_NAME); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(2000); factory.setReadTimeout(10000); final RestTemplate restTemplate = new RestTemplate(factory); final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors .add((final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) -> { final long start = System.nanoTime(); try { return execution.execute(request, body); } finally { pingFederateAPITimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }); restTemplate.setInterceptors(interceptors); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { // Ignore 400 @Override public void handleError(final ClientHttpResponse response) throws IOException { final int errorCode = response.getRawStatusCode(); registry.counter(TOKEN_VALIDATION_ERROR_COUNTER_NAME, Sets.newHashSet(Tag.of(MetricsConstants.TagKeys.STATUS, Integer.toString(errorCode)))) .increment(); if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) { super.handleError(response); } } }); this.setRestTemplate(restTemplate); this.checkTokenEndpointUrl = serverProperties.getTokenInfoUri(); this.clientId = serverProperties.getClientId(); this.clientSecret = serverProperties.getClientSecret(); Assert.state(StringUtils.isNotBlank(this.checkTokenEndpointUrl), "Check Endpoint URL is required"); Assert.state(StringUtils.isNotBlank(this.clientId), "Client ID is required"); Assert.state(StringUtils.isNotBlank(this.clientSecret), "Client secret is required"); log.debug("checkTokenEndpointUrl = {}", this.checkTokenEndpointUrl); log.debug("clientId = {}", this.clientId); log.debug("clientSecret = {}", this.clientSecret); this.converter = converter; }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * Constructor.// www . j a v a 2s . c o m * * @param serverProperties The properties of the resource server (Genie) * @param converter The access token converter to use * @param registry The metrics registry to use */ public PingFederateRemoteTokenServices(@NotNull final ResourceServerProperties serverProperties, @NotNull final AccessTokenConverter converter, @NotNull final Registry registry) { super(); this.tokenValidationError = registry .createId("genie.security.oauth2.pingFederate.tokenValidation.error.rate"); this.authenticationTimer = registry.timer(AUTHENTICATION_TIMER_NAME); this.pingFederateAPITimer = registry.timer(API_TIMER_NAME); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(2000); factory.setReadTimeout(10000); final RestTemplate restTemplate = new RestTemplate(factory); final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors .add((final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) -> { final long start = System.nanoTime(); try { return execution.execute(request, body); } finally { pingFederateAPITimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }); restTemplate.setInterceptors(interceptors); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { // Ignore 400 @Override public void handleError(final ClientHttpResponse response) throws IOException { final int errorCode = response.getRawStatusCode(); registry.counter(tokenValidationError.withTag("status", Integer.toString(errorCode))).increment(); if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) { super.handleError(response); } } }); this.setRestTemplate(restTemplate); this.checkTokenEndpointUrl = serverProperties.getTokenInfoUri(); this.clientId = serverProperties.getClientId(); this.clientSecret = serverProperties.getClientSecret(); Assert.state(StringUtils.isNotBlank(this.checkTokenEndpointUrl), "Check Endpoint URL is required"); Assert.state(StringUtils.isNotBlank(this.clientId), "Client ID is required"); Assert.state(StringUtils.isNotBlank(this.clientSecret), "Client secret is required"); log.debug("checkTokenEndpointUrl = {}", this.checkTokenEndpointUrl); log.debug("clientId = {}", this.clientId); log.debug("clientSecret = {}", this.clientSecret); this.converter = converter; }
From source file:org.springframework.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration.java
void inject(RestTemplate restTemplate) { if (hasTraceInterceptor(restTemplate)) { return;/*from ww w. ja va 2 s . c o m*/ } List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>( restTemplate.getInterceptors()); interceptors.add(0, this.interceptor); restTemplate.setInterceptors(interceptors); }