org.springframework.http.client.ClientHttpRequestInterceptor Java Examples

The following examples show how to use org.springframework.http.client.ClientHttpRequestInterceptor. 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
Source File: Oauth2ClientApplication.java    From training with Apache License 2.0 7 votes vote down vote up
@Bean
RestTemplate restTemplate(OAuth2AuthorizedClientService clientService) {
		return new RestTemplateBuilder()
			.interceptors((ClientHttpRequestInterceptor) (httpRequest, bytes, execution) -> {

					OAuth2AuthenticationToken token = OAuth2AuthenticationToken.class.cast(
						SecurityContextHolder.getContext().getAuthentication());

					OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
						token.getAuthorizedClientRegistrationId(),
						token.getName());

					httpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken().getTokenValue());

					return execution.execute(httpRequest, bytes);
			})
			.build();
}
 
Example #2
Source File: SpringContractWiremockIssueDemoApplication.java    From spring-cloud-contract with Apache License 2.0 7 votes vote down vote up
@Bean
public RestTemplateCustomizer someNotOrderedInterceptorCustomizer() {
	return new RestTemplateCustomizer() {
		@Override
		public void customize(RestTemplate restTemplate) {
			ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() {
				@Override
				public ClientHttpResponse intercept(HttpRequest request, byte[] body,
						ClientHttpRequestExecution execution) throws IOException {
					return execution.execute(request, body);
				}
			};
			restTemplate.getInterceptors().add(emptyInterceptor);
		}
	};
}
 
Example #3
Source File: DubboLoadBalancedRestTemplateAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
/**
 * Adapt the instance of {@link DubboTransporterInterceptor} to the
 * {@link LoadBalancerInterceptor} Bean.
 * @param restTemplate {@link LoadBalanced @LoadBalanced} {@link RestTemplate} Bean
 * @param dubboTranslatedAttributes the annotation dubboTranslatedAttributes
 * {@link RestTemplate} bean being annotated
 * {@link DubboTransported @DubboTransported}
 */
private void adaptRestTemplate(RestTemplate restTemplate,
		Map<String, Object> dubboTranslatedAttributes) {

	List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
			restTemplate.getInterceptors());

	int index = loadBalancerInterceptorBean == null ? -1
			: interceptors.indexOf(loadBalancerInterceptorBean);

	index = index < 0 ? 0 : index;

	// Add ClientHttpRequestInterceptor instances before loadBalancerInterceptor
	interceptors.add(index++, new DubboMetadataInitializerInterceptor(repository));

	interceptors.add(index++,
			new DubboTransporterInterceptor(repository,
					restTemplate.getMessageConverters(), classLoader,
					dubboTranslatedAttributes, serviceFactory, contextFactory));

	restTemplate.setInterceptors(interceptors);
}
 
Example #4
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-15066
public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
	ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
		request.getHeaders().add("MyHeader", "MyInterceptorValue");
		return execution.execute(request, body);
	};
	template.setInterceptors(Collections.singletonList(interceptor));

	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "https://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.add("MyHeader", "MyEntityValue");
	HttpEntity<Void> entity = new HttpEntity<>(null, entityHeaders);
	template.exchange("https://example.com", POST, entity, Void.class);
	assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue"));

	verify(response).close();
}
 
Example #5
Source File: RestExecutorConfiguration.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	ExtRestTemplate restTemplate = (ExtRestTemplate) restExecutor;
	Map<String, Object> restExecutorInterceptors = applicationContext.getBeansWithAnnotation(RestExecutorInterceptor.class);
	if(!LangUtils.isEmpty(restExecutorInterceptors)){
		List<ClientHttpRequestInterceptor> interList = restTemplate.getInterceptors();
		if(interList==null){
			interList = Lists.newArrayList();
			restTemplate.setInterceptors(interList);
		}
		for(Entry<String, Object> entry : restExecutorInterceptors.entrySet()){
			if(logger.isDebugEnabled()){
				logger.debug("register ClientHttpRequestInterceptor for RestExecutor: {}", entry.getKey());
			}
			interList.add((ClientHttpRequestInterceptor)entry.getValue());
		}
		AnnotationAwareOrderComparator.sort(interList);
	}
}
 
Example #6
Source File: TraceRestTemplateInterceptorTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void notSampledHeaderAddedWhenNotSampled() {
	this.tracing.close();
	this.tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
			.addSpanHandler(this.spans).sampler(Sampler.NEVER_SAMPLE).build();
	this.template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
			TracingClientHttpRequestInterceptor.create(HttpTracing.create(tracing))));

	Span span = tracing.tracer().nextSpan().name("new trace");
	Map<String, String> headers;

	try (Tracer.SpanInScope ws = tracing.tracer().withSpanInScope(span.start())) {
		headers = this.template.getForEntity("/", Map.class).getBody();
	}
	finally {
		span.finish();
	}

	then(this.spans).isEmpty();
}
 
Example #7
Source File: PurchaseService.java    From computoser with GNU Affero General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    jsonMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    template.getInterceptors().add(new ClientHttpRequestInterceptor() {

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                throws IOException {
            request.getHeaders().add("Accept", "application/json");
            request.getHeaders().add("Content-Type", "application/json");
            request.getHeaders().add("User-Agent", "");
            return execution.execute(request, body);
        }
    });
    //paymentContext = new PaymillContext(secret);
}
 
Example #8
Source File: TraceWebClientAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
private void assertInterceptorsOrder(
		List<ClientHttpRequestInterceptor> interceptors) {
	int traceInterceptorIndex = -1;
	int myInterceptorIndex = -1;
	int mySecondInterceptorIndex = -1;
	Map<Class, Integer> numberOfInstances = new HashMap<>();
	for (int i = 0; i < interceptors.size(); i++) {
		ClientHttpRequestInterceptor interceptor = interceptors.get(i);
		incrementNumberOfInstances(numberOfInstances, interceptor);
		if (interceptor instanceof TracingClientHttpRequestInterceptor
				|| interceptor instanceof LazyTracingClientHttpRequestInterceptor) {
			traceInterceptorIndex = i;
		}
		else if (interceptor instanceof MyClientHttpRequestInterceptor) {
			myInterceptorIndex = i;
		}
		else if (interceptor instanceof MySecondClientHttpRequestInterceptor) {
			mySecondInterceptorIndex = i;
		}
	}
	then(traceInterceptorIndex).isGreaterThanOrEqualTo(0)
			.isLessThan(myInterceptorIndex).isLessThan(mySecondInterceptorIndex);
	then(numberOfInstances.values())
			.as("Can't have duplicate entries for interceptors")
			.containsOnlyElementsOf(Collections.singletonList(1));
}
 
Example #9
Source File: DataFlowClientAutoConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private ClientHttpRequestInterceptor clientCredentialsTokenResolvingInterceptor(
		ClientRegistration clientRegistration, ClientRegistrationRepository clientRegistrationRepository,
		String clientId) {
	Authentication principal = createAuthentication(clientId);
	OAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService(
			clientRegistrationRepository);
	AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
			clientRegistrationRepository, authorizedClientService);
	OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
			.clientCredentials().build();
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
			.withClientRegistrationId(DEFAULT_REGISTRATION_ID).principal(principal).build();

	return (request, body, execution) -> {
		OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
		request.getHeaders().setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
		return execution.execute(request, body);
	};
}
 
Example #10
Source File: OneDriveConfig.java    From zfile with MIT License 6 votes vote down vote up
/**
 * OneDrive 请求 RestTemplate, 会在请求头中添加 Bearer: Authorization {token} 信息, 用于 API 认证.
 */
@Bean
public RestTemplate oneDriveRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();

    ClientHttpRequestInterceptor interceptor = (httpRequest, bytes, clientHttpRequestExecution) -> {
        HttpHeaders headers = httpRequest.getHeaders();
        Integer driveId = Integer.valueOf(((LinkedList)headers.get("driveId")).get(0).toString());

        StorageConfig accessTokenConfig =
                storageConfigService.findByDriveIdAndKey(driveId, StorageConfigConstant.ACCESS_TOKEN_KEY);

        String tokenValue = String.format("%s %s", "Bearer", accessTokenConfig.getValue());
        httpRequest.getHeaders().add("Authorization", tokenValue);
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    };
    restTemplate.setInterceptors(Collections.singletonList(interceptor));
    return restTemplate;
}
 
Example #11
Source File: ConfigCommands.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private ClientHttpRequestInterceptor bearerTokenResolvingInterceptor(
		OAuth2ClientProperties properties, String username, String password, String clientRegistrationId) {
	ClientRegistrationRepository shellClientRegistrationRepository = shellClientRegistrationRepository(properties);
	OAuth2AuthorizedClientService shellAuthorizedClientService = shellAuthorizedClientService(shellClientRegistrationRepository);
	OAuth2AuthorizedClientManager authorizedClientManager = authorizedClientManager(
			shellClientRegistrationRepository, shellAuthorizedClientService);

	if (properties.getRegistration() != null && properties.getRegistration().size() == 1) {
		// if we have only one, use that
		clientRegistrationId = properties.getRegistration().entrySet().iterator().next().getKey();
	}

	OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
			.principal(DEFAULT_PRINCIPAL)
			.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username)
			.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password)
			.build();

	return (request, body, execution) -> {
		OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
		request.getHeaders().setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
		return execution.execute(request, body);
	};
}
 
Example #12
Source File: ConfigServicePropertySourceLocatorTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void checkInterceptorHasNoAuthorizationHeaderPresent() {
	ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
	defaults.getHeaders().put(AUTHORIZATION, "Basic dXNlcm5hbWU6cGFzc3dvcmQNCg==");
	defaults.getHeaders().put("key", "value");
	this.locator = new ConfigServicePropertySourceLocator(defaults);
	RestTemplate restTemplate = ReflectionTestUtils.invokeMethod(this.locator,
			"getSecureRestTemplate", defaults);
	Iterator<ClientHttpRequestInterceptor> iterator = restTemplate.getInterceptors()
			.iterator();
	while (iterator.hasNext()) {
		GenericRequestHeaderInterceptor genericRequestHeaderInterceptor = (GenericRequestHeaderInterceptor) iterator
				.next();
		assertThat(genericRequestHeaderInterceptor.getHeaders().get(AUTHORIZATION))
				.isEqualTo(null);
	}
}
 
Example #13
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-15066
public void requestInterceptorCanAddExistingHeaderValueWithBody() throws Exception {
	ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
		request.getHeaders().add("MyHeader", "MyInterceptorValue");
		return execution.execute(request, body);
	};
	template.setInterceptors(Collections.singletonList(interceptor));

	MediaType contentType = MediaType.TEXT_PLAIN;
	given(converter.canWrite(String.class, contentType)).willReturn(true);
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "http://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(contentType);
	entityHeaders.add("MyHeader", "MyEntityValue");
	HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders);
	template.exchange("http://example.com", POST, entity, Void.class);
	assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue"));

	verify(response).close();
}
 
Example #14
Source File: SpringContractWiremockIssueDemoApplication.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Bean
@Order
public RestTemplateCustomizer someLowestPrecedenceOrderedInterceptorCustomizer() {
	return new RestTemplateCustomizer() {
		@Override
		public void customize(RestTemplate restTemplate) {
			ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() {
				@Override
				public ClientHttpResponse intercept(HttpRequest request, byte[] body,
						ClientHttpRequestExecution execution) throws IOException {
					return execution.execute(request, body);
				}
			};
			restTemplate.getInterceptors().add(emptyInterceptor);
		}
	};
}
 
Example #15
Source File: FitbitAuthorizationCodeAccessTokenProvider.java    From shimmer with Apache License 2.0 6 votes vote down vote up
/**
 * Add any interceptors found in the application context, e.g. for logging, which may or may not be present
 * based on profiles.
 */
@Autowired(required = false)
@Override
public void setInterceptors(List<ClientHttpRequestInterceptor> interceptors) {

    if (interceptors.isEmpty()) {
        logger.info("No HTTP request interceptors have been found in the application context.");
        return;
    }

    for (ClientHttpRequestInterceptor interceptor : interceptors) {
        logger.info("The interceptor '{}' will be added to this provider.", interceptor.getClass().getSimpleName());
    }

    super.setInterceptors(interceptors);
}
 
Example #16
Source File: SpringContractWiremockIssueDemoApplication.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Bean
@Order(SOME_NOT_LOWEST_PRECEDENCE)
@Profile("bug")
public RestTemplateCustomizer someOrderedInterceptorCustomizer() {
	return new RestTemplateCustomizer() {
		@Override
		public void customize(RestTemplate restTemplate) {
			ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() {
				@Override
				public ClientHttpResponse intercept(HttpRequest request, byte[] body,
						ClientHttpRequestExecution execution) throws IOException {
					return execution.execute(request, body);
				}
			};
			restTemplate.getInterceptors().add(emptyInterceptor);
		}
	};
}
 
Example #17
Source File: FormLoginAuthenticationCsrfTokenInterceptor.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Init
 */
@PostConstruct
protected void init() {

    restTemplateForAuthenticationFlow = new CookieStoreRestTemplate();
    cookieStore = restTemplateForAuthenticationFlow.getCookieStore();

    logger.debug("Inject cookie store used in the rest template for authentication flow into the authRestTemplate so that they will match");
    authRestTemplate.restTemplate.setCookieStoreAndUpdateRequestFactory(cookieStore);

    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor>singletonList(new ClientHttpRequestInterceptor() {
                @Override
                public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                    if (latestCsrfToken != null) {
                        // At the beginning of auth flow, there's no token yet
                        injectCsrfTokenIntoHeader(request, latestCsrfToken);
                    }
                    return execution.execute(request, body);
                }
            });

    restTemplateForAuthenticationFlow.setRequestFactory(new InterceptingClientHttpRequestFactory(restTemplateForAuthenticationFlow.getRequestFactory(), interceptors));
}
 
Example #18
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-15066
public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
	ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
		request.getHeaders().add("MyHeader", "MyInterceptorValue");
		return execution.execute(request, body);
	};
	template.setInterceptors(Collections.singletonList(interceptor));

	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "http://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.add("MyHeader", "MyEntityValue");
	HttpEntity<Void> entity = new HttpEntity<>(null, entityHeaders);
	template.exchange("http://example.com", POST, entity, Void.class);
	assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue"));

	verify(response).close();
}
 
Example #19
Source File: StandardDirectorUtils.java    From chaos-lemur with Apache License 2.0 6 votes vote down vote up
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
        new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .useTLS()
        .build();

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create()
        .disableRedirectHandling()
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLSocketFactory(connectionFactory)
        .build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}
 
Example #20
Source File: AviRestUtils.java    From sdk with Apache License 2.0 6 votes vote down vote up
public static RestTemplate getRestTemplate(AviCredentials creds) {
	RestTemplate restTemplate = null;
	if (creds != null) {
		try {
			restTemplate = getInitializedRestTemplate(creds);
			restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(getControllerURL(creds) + API_PREFIX));
			List<ClientHttpRequestInterceptor> interceptors = 
					Collections.<ClientHttpRequestInterceptor>singletonList(
							new AviAuthorizationInterceptor(creds));
			restTemplate.setInterceptors(interceptors);
			restTemplate.setMessageConverters(getMessageConverters(restTemplate));
			return restTemplate;
		} catch (Exception e) {
			LOGGER.severe("Exception during rest template initialization");

		}
	}
	return restTemplate;
}
 
Example #21
Source File: CloudFoundryClientFactory.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: TraceWebClientAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private boolean hasTraceInterceptor(RestTemplate restTemplate) {
	for (ClientHttpRequestInterceptor interceptor : restTemplate.getInterceptors()) {
		if (interceptor instanceof TracingClientHttpRequestInterceptor
				|| interceptor instanceof LazyTracingClientHttpRequestInterceptor) {
			return true;
		}
	}
	return false;
}
 
Example #23
Source File: DtmRestTemplateAutoConfiguration.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
  LOGGER.debug("init restTemplate for dtm..");
  if (this.restTemplates != null) {
    for (RestTemplate restTemplate : restTemplates) {
      List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
          restTemplate.getInterceptors());
      interceptors.add(dtmRestTemplateInterceptor);
      restTemplate.setInterceptors(interceptors);
    }
  }
}
 
Example #24
Source File: HttpBasicAuthenticationSecurityConfigurationUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaObjectInitializerPostProcessorProcessesClusterSchemaObjectInitializerBeans() throws Exception {

	Environment mockEnvironment = mock(Environment.class);

	ClientCache mockClientCache = mock(ClientCache.class);

	ClusterConfigurationConfiguration.SchemaObjectContext schemaObjectContextSpy =
		spy(constructInstance(ClusterConfigurationConfiguration.SchemaObjectContext.class,
			new Class[] { GemFireCache.class }, mockClientCache));

	assertThat(schemaObjectContextSpy).isNotNull();
	assertThat(schemaObjectContextSpy.<ClientCache>getGemfireCache()).isEqualTo(mockClientCache);

	doReturn(new RestHttpGemfireAdminTemplate(mockClientCache))
		.when(schemaObjectContextSpy).getGemfireAdminOperations();

	ClusterConfigurationConfiguration.ClusterSchemaObjectInitializer clusterSchemaObjectInitializer =
		constructInstance(ClusterConfigurationConfiguration.ClusterSchemaObjectInitializer.class,
			new Class[] { ClusterConfigurationConfiguration.SchemaObjectContext.class }, schemaObjectContextSpy);

	BeanPostProcessor beanPostProcessor =
		this.httpSecurityConfiguration.schemaObjectInitializerPostProcessor(mockEnvironment);

	assertThat(beanPostProcessor).isNotNull();
	assertThat(beanPostProcessor.postProcessBeforeInitialization(clusterSchemaObjectInitializer,
		"mockClusterSchemaObjectInitializer")).isEqualTo(clusterSchemaObjectInitializer);
	assertThat(beanPostProcessor.postProcessAfterInitialization(clusterSchemaObjectInitializer,
		"mockClusterSchemaObjectInitializer")).isEqualTo(clusterSchemaObjectInitializer);
	assertThat(this.httpSecurityConfiguration.restTemplateReference.get()).isNotNull();
	assertThat(this.httpSecurityConfiguration.restTemplateReference.get().getInterceptors()).isNotEmpty();
	assertThat(this.httpSecurityConfiguration.restTemplateReference.get().getInterceptors().stream()
		.anyMatch(ClientHttpRequestInterceptor.class::isInstance)).isTrue();
}
 
Example #25
Source File: Application.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@Bean
public UserInfoRestTemplateCustomizer userInfoRestTemplateCustomizer(
        TraceRestTemplateInterceptor traceRestTemplateInterceptor) {
    return restTemplate -> {
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
                restTemplate.getInterceptors());
        interceptors.add(traceRestTemplateInterceptor);
        restTemplate.setInterceptors(interceptors);
    };
}
 
Example #26
Source File: Application.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@Bean
public UserInfoRestTemplateCustomizer userInfoRestTemplateCustomizer(
        TraceRestTemplateInterceptor traceRestTemplateInterceptor) {
    return restTemplate -> {
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
                restTemplate.getInterceptors());
        interceptors.add(traceRestTemplateInterceptor);
        restTemplate.setInterceptors(interceptors);
    };
}
 
Example #27
Source File: ConfigClientConfiguration.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
 * copy form ConfigServicePropertySourceLocator#getSecureRestTemplate
 * @author weishao zeng
 * @param client
 * @return
 */
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 username = client.getUsername();
	String password = client.getPassword();
	String authorization = client.getAuthorization();
	Map<String, String> headers = new HashMap<>(client.getHeaders());

	if (password != null && authorization != null) {
		throw new IllegalStateException(
				"You must set either 'password' or 'authorization'");
	}

	if (password != null) {
		byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
		headers.put("Authorization", "Basic " + new String(token));
	}
	else if (authorization != null) {
		headers.put("Authorization", authorization);
	}

	if (!headers.isEmpty()) {
		template.setInterceptors(Arrays.<ClientHttpRequestInterceptor> asList(
				new GenericRequestHeaderInterceptor(headers)));
	}

	return template;
}
 
Example #28
Source File: RestTemplateTracingTransmitter.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
@Autowired
public RestTemplateTracingTransmitter(@Autowired(required = false) List<RestTemplate> restTemplates) {
    if (Objects.nonNull(restTemplates)) {
        restTemplates.forEach(restTemplate -> {
            List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
            interceptors.add(interceptors.size(), RestTemplateTracingTransmitter.this);
        });
    }
}
 
Example #29
Source File: TestRestTemplateWrapper.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void setInterceptorsWithUnderlying() {
  ClientHttpRequestInterceptor interceptor1 = mock(ClientHttpRequestInterceptor.class);
  ClientHttpRequestInterceptor interceptor2 = mock(ClientHttpRequestInterceptor.class);
  List<ClientHttpRequestInterceptor> interceptors = asList(interceptor1, interceptor2);

  wrapper.setInterceptors(interceptors);

  assertThat(wrapper.getInterceptors(), contains(interceptor1, interceptor2));
  assertThat(wrapper.defaultRestTemplate.getInterceptors(), contains(interceptor1, interceptor2));
  verify(underlying, never()).setInterceptors(interceptors);
}
 
Example #30
Source File: RetryLoadBalancerAutoConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertLoadBalanced(RestTemplate restTemplate) {
	List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
	then(interceptors).hasSize(1);
	ClientHttpRequestInterceptor interceptor = interceptors.get(0);
	then(interceptor).isInstanceOf(RetryLoadBalancerInterceptor.class);
}