Java Code Examples for org.springframework.boot.web.client.RestTemplateBuilder

The following examples show how to use org.springframework.boot.web.client.RestTemplateBuilder. 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
Source Project: training   Source File: Oauth2ClientApplication.java    License: 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
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {

    SSLContext sslContext = SSLContextBuilder
            .create()
            .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"), allPassword, allPassword)
            .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword)
            .build();

    HttpClient client = HttpClients.custom()
            .setSSLContext(sslContext)
            .build();

    return builder
            .requestFactory(new HttpComponentsClientHttpRequestFactory(client))
            .build();
}
 
Example 3
@Bean
@Lazy
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder(ObjectProvider<HttpMessageConverters> messageConverters,
                                               ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers,
                                               ObjectProvider<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers,
                                               OkHttpClient okHttpClient) {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    HttpMessageConverters converters = messageConverters.getIfUnique();
    if (converters != null) {
        builder = builder.messageConverters(converters.getConverters());
    }
    builder = addCustomizers(builder, restTemplateCustomizers, RestTemplateBuilder::customizers);
    builder = addCustomizers(builder, restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);

    builder = builder.requestFactory(() -> new OkHttp3ClientHttpRequestFactory(okHttpClient));

    return builder;
}
 
Example 4
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    // configure a net binding instance
    Net mongoNet = this.getMongoNet();

    // register some autowire-able dependencies, to make leveraging the configured instances in a test possible
    applicationContext.getBeanFactory().registerResolvableDependency(RestTemplateBuilder.class, this.getRestTemplateBuilder());
    applicationContext.getBeanFactory().registerResolvableDependency(Net.class, mongoNet);
    applicationContext.getBeanFactory().registerResolvableDependency(MongodExecutable.class, this.getMongo(mongoNet));

    // configure the property sources that will be used by the application
    MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
    MockPropertySource mockEnvVars = new MockPropertySource()
            .withProperty(Constants.ENV_DB_NAME, this.getDbName())
            .withProperty(Constants.ENV_DB_CONNSTR, "mongodb://localhost:" + mongoNet.getPort())
            .withProperty(Constants.ENV_ALLOWED_ORIGIN, this.getAllowedOrigin())
            .withProperty(Constants.ENV_EXCLUDE_FILTER, String.join(",", this.getExcludeList()));

    // inject the property sources into the application as environment variables
    propertySources.replace(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, mockEnvVars);
}
 
Example 5
@Bean
@Lazy
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder(ObjectProvider<HttpMessageConverters> messageConverters,
                                               ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers,
                                               ObjectProvider<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers,
                                               OkHttpClient okHttpClient) {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    HttpMessageConverters converters = messageConverters.getIfUnique();
    if (converters != null) {
        builder = builder.messageConverters(converters.getConverters());
    }
    builder = addCustomizers(builder, restTemplateCustomizers, RestTemplateBuilder::customizers);
    builder = addCustomizers(builder, restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);

    builder = builder.requestFactory(() -> new OkHttp3ClientHttpRequestFactory(okHttpClient));

    return builder;
}
 
Example 6
Source Project: waggle-dance   Source File: WaggleDanceIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void metastoreTunnelConfiguration() throws Exception {
  String route = "[email protected] -> [email protected]";
  String privateKeys = "/home/user/.ssh/bastion-key-pair.pem,/home/user/.ssh/emr-key-pair.pem";
  String knownHosts = "/home/user/.ssh/known_hosts";
  runner = WaggleDanceRunner
      .builder(configLocation)
      .primary("primary", localServer.getThriftConnectionUri(), READ_ONLY)
      .federateWithMetastoreTunnel(SECONDARY_METASTORE_NAME, remoteServer.getThriftConnectionUri(), REMOTE_DATABASE,
          route, privateKeys, knownHosts)
      .build();

  runWaggleDance(runner);
  RestTemplate rest = new RestTemplateBuilder().build();
  FederatedMetaStore federatedMetastore = rest
      .getForObject(
          "http://localhost:" + runner.getRestApiPort() + "/api/admin/federations/" + SECONDARY_METASTORE_NAME,
          FederatedMetaStore.class);

  MetastoreTunnel metastoreTunnel = federatedMetastore.getMetastoreTunnel();
  assertThat(metastoreTunnel.getRoute(), is(route));
  assertThat(metastoreTunnel.getKnownHosts(), is(knownHosts));
  assertThat(metastoreTunnel.getPrivateKeys(), is(privateKeys));
}
 
Example 7
private void configureService(StatsProperties properties) {
	ProjectRequestDocumentFactory documentFactory = new ProjectRequestDocumentFactory();
	this.retryTemplate = new RetryTemplate();
	this.statPublisher = new ProjectGenerationStatPublisher(documentFactory, properties, new RestTemplateBuilder(),
			this.retryTemplate);
	this.mockServer = MockRestServiceServer.createServer(this.statPublisher.getRestTemplate());
}
 
Example 8
Source Project: Milkomeda   Source File: EchoConfig.java    License: MIT License 5 votes vote down vote up
@Bean("echoRestTemplate")
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public RestTemplate simpleRestTemplate(RestTemplateBuilder builder) {
    RestTemplate restTemplate = builder.build();
    restTemplate.setRequestFactory(clientHttpRequestFactory());
    // 自定义错误处理
    restTemplate.setErrorHandler(new EchoResponseErrorHandler());
    return restTemplate;
}
 
Example 9
Source Project: initializr   Source File: ProjectGenerationStatPublisher.java    License: Apache License 2.0 5 votes vote down vote up
public ProjectGenerationStatPublisher(ProjectRequestDocumentFactory documentFactory,
		StatsProperties statsProperties, RestTemplateBuilder restTemplateBuilder, RetryTemplate retryTemplate) {
	this.documentFactory = documentFactory;
	this.objectMapper = createObjectMapper();
	StatsProperties.Elastic elastic = statsProperties.getElastic();
	UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(determineEntityUrl(elastic));
	this.restTemplate = configureAuthorization(restTemplateBuilder, elastic, uriBuilder).build();
	this.requestUrl = uriBuilder.userInfo(null).build().toUri();
	this.retryTemplate = retryTemplate;
}
 
Example 10
Source Project: tutorials   Source File: TestRestTemplateBasicLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() {
    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    restTemplateBuilder.configure(restTemplate);
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd");
    ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
            String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example 11
@Bean
public RestTemplate restTemplate() {
  return new RestTemplateBuilder()
          .requestFactory(this::clientHttpRequestFactory)
          .errorHandler(new CustomClientErrorHandler())
          .interceptors(new CustomClientHttpRequestInterceptor())
          .build();
}
 
Example 12
@Bean
RestTemplate restTemplateWithConnectReadTimeout() {
    return new RestTemplateBuilder()
        .setConnectTimeout(Duration.ofMillis(TIMEOUT))
        .setReadTimeout(Duration.ofMillis(TIMEOUT))
        .build();
}
 
Example 13
private RestTemplateBuilder initRestTemplateBuilder(RestTemplateBuilder builder) {
	StringHttpMessageConverter octetToStringMessageConverter = new StringHttpMessageConverter();
	List<MediaType> mediaTypeList = new ArrayList(octetToStringMessageConverter.getSupportedMediaTypes());
	mediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
	octetToStringMessageConverter.setSupportedMediaTypes(mediaTypeList);

	return builder.additionalMessageConverters(octetToStringMessageConverter);
}
 
Example 14
public GithubService(RestTemplateBuilder builder, ApplicationProperties properties) {
	String username = properties.getGithub().getUsername();
	String password = properties.getGithub().getPassword();
	if (StringUtils.hasLength(username)) {
		builder = builder.basicAuthentication(username, password);
	}
	builder = builder.rootUri(properties.getGithub().getApiUrl());
	this.restTemplate = builder.build();
}
 
Example 15
Source Project: apm-agent-java   Source File: SpringBoot1_5IT.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    MockTracer.MockInstrumentationSetup mockInstrumentationSetup = MockTracer.getOrCreateInstrumentationTracer();
    config = mockInstrumentationSetup.getConfig();
    reporter = mockInstrumentationSetup.getReporter();
    ElasticApmAgent.initInstrumentation(mockInstrumentationSetup.getTracer(), ByteBuddyAgent.install());
    restTemplate = new TestRestTemplate(new RestTemplateBuilder().setConnectTimeout(0).setReadTimeout(0));
}
 
Example 16
Source Project: n2o-framework   Source File: N2oEngineConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "restDataProviderEngine")
public SpringRestDataProviderEngine restDataProviderEngine(RestTemplateBuilder builder) {
    ObjectMapper restObjectMapper = restObjectMapper();
    SpringRestDataProviderEngine springRestDataProviderEngine = new SpringRestDataProviderEngine(
            restTemplate(builder, httpMessageConverter(restObjectMapper)),
            restObjectMapper);
    springRestDataProviderEngine.setBaseRestUrl(baseRestUrl);
    return springRestDataProviderEngine;
}
 
Example 17
Source Project: java-specialagent   Source File: SpringWebFluxTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
  APPLICATION_CONTEXT.registerBean("jettyReactiveWebServerFactory", JettyReactiveWebServerFactory.class, () -> new JettyReactiveWebServerFactory(0));
  APPLICATION_CONTEXT.registerBean("httpHandler", HttpHandler.class, () -> WebHttpHandlerBuilder.applicationContext(APPLICATION_CONTEXT).build());
  APPLICATION_CONTEXT.registerBean("webHandler", WebHandler.class, () -> SpringWebFluxTest::handler);
  APPLICATION_CONTEXT.refresh();

  final int serverPort = APPLICATION_CONTEXT.getWebServer().getPort();
  testRestTemplate = new TestRestTemplate(new RestTemplateBuilder().rootUri("http://127.0.0.1:" + serverPort));
}
 
Example 18
Source Project: servicecomb-pack   Source File: RestTemplateConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "omegaRestTemplate")
public RestTemplate omegaRestTemplate(@Autowired(required = false) OmegaContext context,
    RestTemplateBuilder restTemplateBuilder) {
  return restTemplateBuilder
      .additionalInterceptors(new TransactionClientHttpRequestInterceptor(context))
      .build();
}
 
Example 19
Source Project: tutorials   Source File: TestRestTemplateBasicLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    restTemplateBuilder.configure(restTemplate);
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
    ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example 20
Source Project: initializr   Source File: ProjectGenerationStatPublisher.java    License: Apache License 2.0 5 votes vote down vote up
private static RestTemplateBuilder configureAuthorization(RestTemplateBuilder restTemplateBuilder, Elastic elastic,
		UriComponentsBuilder uriComponentsBuilder) {
	String userInfo = uriComponentsBuilder.build().getUserInfo();
	if (StringUtils.hasText(userInfo)) {
		String[] credentials = userInfo.split(":");
		return restTemplateBuilder.basicAuthentication(credentials[0], credentials[1]);
	}
	else if (StringUtils.hasText(elastic.getUsername())) {
		return restTemplateBuilder.basicAuthentication(elastic.getUsername(), elastic.getPassword());
	}
	return restTemplateBuilder;
}
 
Example 21
Source Project: tutorials   Source File: TestRestTemplateBasicLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    restTemplateBuilder.configure(restTemplate);
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
    ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example 22
Source Project: springbootexamples   Source File: RestTemplateConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
	//return builder.build();
	return builder
			.setConnectTimeout(Duration.ofMillis(100))
			.setReadTimeout(Duration.ofMillis(500))
			.requestFactory(this::requestFactory)
			.build();
}
 
Example 23
Source Project: springbootexamples   Source File: RestTemplateConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
	//return builder.build();
	return builder
			.setConnectTimeout(Duration.ofMillis(100))
			.setReadTimeout(Duration.ofMillis(500))
			.requestFactory(this::requestFactory)
			.build();
}
 
Example 24
Source Project: sms   Source File: LinkSMSConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
	return builder
			.rootUri(baseUrl)
			.messageConverters(formHttpMessageConverter(), stringHttpMessageConverter())
			.build();
}
 
Example 25
@Bean
@ConditionalOnMissingBean
public BlockingRegistrationClient registrationClient(ClientProperties client) {
	RestTemplateBuilder builder = new RestTemplateBuilder().setConnectTimeout(client.getConnectTimeout())
			.setReadTimeout(client.getReadTimeout());
	if (client.getUsername() != null && client.getPassword() != null) {
		builder = builder.basicAuthentication(client.getUsername(), client.getPassword());
	}
	return new BlockingRegistrationClient(builder.build());
}
 
Example 26
Source Project: MicroCommunity   Source File: ApiApplicationStart.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 实例化RestTemplate
 *
 * @return restTemplate
 */
@Bean
public RestTemplate outRestTemplate() {
    StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build(RestTemplate.class);
    return restTemplate;
}
 
Example 27
/**
 * 实例化RestTemplate
 *
 * @return restTemplate
 */
@Bean
public com.java110.core.client.RestTemplate outRestTemplate() {
    StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    com.java110.core.client.RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build(com.java110.core.client.RestTemplate.class);
    return restTemplate;
}
 
Example 28
/**
 * 实例化RestTemplate
 *
 * @return restTemplate
 */
@Bean
public com.java110.core.client.RestTemplate outRestTemplate() {
    StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    com.java110.core.client.RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build(com.java110.core.client.RestTemplate.class);
    return restTemplate;
}
 
Example 29
Source Project: tutorials   Source File: TestRestTemplateBasicLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() {
    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    restTemplateBuilder.build();
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
    ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example 30
Source Project: genie   Source File: ApisAutoConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Make sure we get a valid rest template to use.
 */
@Test
void canGetRestTemplate() {
    Assertions
        .assertThat(this.apisAutoConfiguration.genieRestTemplate(new HttpProperties(), new RestTemplateBuilder()))
        .isNotNull();
}