Java Code Examples for org.springframework.web.client.RestTemplate#setInterceptors()

The following examples show how to use org.springframework.web.client.RestTemplate#setInterceptors() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Bean
public SmartInitializingSingleton loadBalancedRestTemplateInitializer2(
        final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) {
    return () -> {
        logger.info("RestTemplateResilienceAutoConfiguration init2");
        for (RestTemplate restTemplate : RestTemplateCircuitBreakerAutoConfiguration.this.restTemplates) {
            List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
            logger.info("RestTemplate init2 start,interceptor size:" + interceptors.size());
            //for (ClientHttpRequestInterceptor interceptor : interceptors) {
            //logger.info("RestTemplate init2 interceptor ing:"+interceptor.getClass().getCanonicalName());
            //}
            //logger.info("RestTemplate init2 Customizer end");
            ClientHttpRequestInterceptor interceptor1 = new RestTemplateCircuitBreakerInterceptor
                    (circuitBreakerCore);
            interceptors.add(0, interceptor1);
            restTemplate.setInterceptors(interceptors);
            logger.info("RestTemplate init2 end,add CircuitBreaker interceptor");
        }
    };
}
 
Example 2
private RestTemplate getSecureRestTemplate(ConfigClientProperties properties) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    if (properties.getRequestReadTimeout() < 0) {
        throw new IllegalStateException("Invalid Value for Real Timeout set.");
    }

    requestFactory.setReadTimeout(properties.getRequestReadTimeout());
    RestTemplate template = new RestTemplate(requestFactory);
    Map<String, String> headers = new HashMap<>(properties.getHeaders());
    headers.remove(AUTHORIZATION); // To avoid redundant addition of header

    if (!headers.isEmpty()) {
        template.setInterceptors(Collections.singletonList(new GenericRequestHeaderInterceptor(headers)));
    }

    return template;
}
 
Example 3
@Override
public void afterPropertiesSet() throws Exception {
    if (null != restTemplateList) {
        for (RestTemplate restTemplate : restTemplateList) {
            List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
            if (interceptors == null) {
                restTemplate.setInterceptors(Arrays.asList(grayClientHttpRequestInterceptor));
            } else {
                List<ClientHttpRequestInterceptor> newInterceptors = new ArrayList<>();
                newInterceptors.addAll(interceptors);
                newInterceptors.add(grayClientHttpRequestInterceptor);
                restTemplate.setInterceptors(newInterceptors);
            }
        }
    }
}
 
Example 4
protected final AllureResults execute() {
    final RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
    restTemplate.setInterceptors(Collections.singletonList(new AllureRestTemplate()));

    final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort());

    return runWithinTestContext(() -> {
        server.start();
        WireMock.configureFor(server.port());
        WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/hello")).willReturn(WireMock.aResponse().withBody("some body")));
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<JsonNode> entity = new HttpEntity<>(headers);
            ResponseEntity<String> result = restTemplate.exchange(server.url("/hello"), HttpMethod.GET, entity, String.class);
            Assertions.assertEquals(result.getStatusCode(), HttpStatus.OK);
        } finally {
            server.stop();
        }
    });
}
 
Example 5
/** {@inheritDoc} */
@Override
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);
		LOG.debug("rest template interceptor initialized");
	}

	return bean;
}
 
Example 6
/**
 * Create rest template.
 * 
 * @param readTimeout
 * @return
 */
public RestTemplate createRestTemplate(long readTimeout) {
	Assert.state(readTimeout > 0, String.format("Invalid value for read timeout for %s", readTimeout));

	Netty4ClientHttpRequestFactory factory = new Netty4ClientHttpRequestFactory();
	factory.setConnectTimeout(config.getConnectTimeout());
	factory.setReadTimeout((int) readTimeout);
	factory.setMaxResponseSize(config.getMaxResponseSize());
	RestTemplate restTemplate = new RestTemplate(factory);

	Map<String, String> headers = new HashMap<>(config.getHeaders());
	if (headers.containsKey(AUTHORIZATION)) {
		// To avoid redundant addition of header
		headers.remove(AUTHORIZATION);
	}
	if (!headers.isEmpty()) {
		restTemplate.setInterceptors(asList(new GenericRequestHeaderInterceptor(headers)));
	}
	return restTemplate;
}
 
Example 7
private void addTaggingInterceptor(RestTemplate template, String org, String space) {
    if (template.getInterceptors()
                .isEmpty()) {
        template.setInterceptors(new ArrayList<>());
    }
    ClientHttpRequestInterceptor requestInterceptor = new TaggingRequestInterceptor(configuration.getVersion(), org, space);
    template.getInterceptors()
            .add(requestInterceptor);
}
 
Example 8
/**
 * 使用带有Ribbon 功能的Spring RestTemplate
 */
@LoadBalanced
@Bean
@SuppressWarnings("unchecked")
public RestTemplate getRestTemplate(){
    RestTemplate restTemplate = new RestTemplate();
    //加上拦截器,发出请求前加入管理id Header
    List interceptors = restTemplate.getInterceptors();
    if(interceptors==null){
        restTemplate.setInterceptors(Collections.singletonList(new UserContextInterceptor()));
    }else{
        interceptors.add(new UserContextInterceptor());
    }
    return restTemplate;
}
 
Example 9
Source Project: txle   File: RestTemplateConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RestTemplate restTemplate(@Autowired(required = false) OmegaContext context, @Autowired Tracing tracing) {
  RestTemplate template = new RestTemplate();
  List<ClientHttpRequestInterceptor> interceptors = template.getInterceptors();
  interceptors.add(new TransactionClientHttpRequestInterceptor(context));
  // add interceptor for rest's request server By Gannalyo
  interceptors.add(TracingClientHttpRequestInterceptor.create(tracing));
  template.setInterceptors(interceptors);
  return template;
}
 
Example 10
void inject(RestTemplate restTemplate) {
	if (hasTraceInterceptor(restTemplate)) {
		return;
	}
	List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(
			restTemplate.getInterceptors());
	interceptors.add(0, this.interceptor);
	restTemplate.setInterceptors(interceptors);
}
 
Example 11
/**
 * Make a REST call with custom headers
 * 
 * @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;
	}
}
 
Example 12
Source Project: chassis   File: WebSocketDocsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProtobufMessagesSchema() 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", "false");
	
	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);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));

		ResponseEntity<String> response = httpClient.getForEntity(
				new URI("http://localhost:" + properties.get("admin.port") + "/schema/messages/protobuf"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().contains("message error"));
	} finally {
		context.close();
	}
}
 
Example 13
Source Project: sample-boot-micro   File: MicroWebConfig.java    License: MIT License 5 votes vote down vote up
/**
 * Ribbon 経由で Eureka がサポートしているサービスを実行するための RestTemplate。
 * <p>リクエスト時に利用者情報を紐づけています。
 */
@Bean
@LoadBalanced
RestTemplate restTemplate(ActorSession session) {
    RestTemplate tmpl = new RestTemplate();
    tmpl.setInterceptors(new ArrayList<>(Arrays.asList(
        new RestActorSessionInterceptor(session)
    )));
    return tmpl;
}
 
Example 14
public void enhanceRestTemplateWithSofaTracer(RestTemplate restTemplate) {
    // check interceptor
    if (checkRestTemplateInterceptor(restTemplate)) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
        restTemplate.getInterceptors());
    interceptors.add(0, this.restTemplateInterceptor);
    restTemplate.setInterceptors(interceptors);
}
 
Example 15
private void processing(RestTemplate restTemplate) {
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
    interceptors.add(new TraceClientHttpRequestInterceptor(traceContentFactory));
    restTemplate.setInterceptors(interceptors);
}
 
Example 16
Source Project: chassis   File: SharedTest.java    License: Apache License 2.0 4 votes vote down vote up
@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 {
		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();
	}
}
 
Example 17
@Override protected void options(ClientHttpRequestFactory client, String path) {
  RestTemplate restTemplate = new RestTemplate(client);
  restTemplate.setInterceptors(Collections.singletonList(interceptor));
  restTemplate.optionsForAllow(url(path), String.class);
}
 
Example 18
Source Project: chassis   File: SharedTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testClassPath() 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 {
		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/classpath"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().length() > 0);
	} finally {
		context.close();
	}
}
 
Example 19
@Override protected void post(ClientHttpRequestFactory client, String uri, String content) {
  RestTemplate restTemplate = new RestTemplate(client);
  restTemplate.setInterceptors(Collections.singletonList(interceptor));
  restTemplate.postForObject(url(uri), content, String.class);
}
 
Example 20
Source Project: chassis   File: SharedTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testHealthcheck() 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 {
		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") + "/healthcheck"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertEquals("OK", response.getBody());
	} finally {
		context.close();
	}
}