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

The following examples show how to use org.springframework.boot.web.client.RestTemplateBuilder. 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: RestClientCertTestConfiguration.java    From spring-boot-rest-clientcertificate with MIT License 8 votes vote down vote up
@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 #2
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 #3
Source File: PropertyMockingApplicationContextInitializer.java    From entref-spring-boot with MIT License 6 votes vote down vote up
@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 #4
Source File: OkHttpRestTemplateAutoConfiguration.java    From okhttp-spring-boot with MIT License 6 votes vote down vote up
@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 #5
Source File: WaggleDanceIntegrationTest.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
@Test
public void metastoreTunnelConfiguration() throws Exception {
  String route = "ec2-user@bastion-host -> hadoop@emr-master";
  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 #6
Source File: OkHttpRestTemplateAutoConfiguration.java    From okhttp-spring-boot with MIT License 6 votes vote down vote up
@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 #7
Source File: IssueTrackerConfiguration.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
@Bean
@Qualifier("tracker")
RestTemplateBuilder restTemplate() {

	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	converter.setObjectMapper(jacksonObjectMapper());

	return new RestTemplateBuilder().messageConverters(converter)
			.requestFactory(HttpComponentsClientHttpRequestFactory.class);
}
 
Example #8
Source File: N2oEngineConfiguration.java    From n2o-framework with 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 #9
Source File: CommunityServiceApplicationStart.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 实例化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 #10
Source File: SpringBoot1_5IT.java    From apm-agent-java with 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 #11
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with 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 #12
Source File: ApisAutoConfigurationTest.java    From genie with 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();
}
 
Example #13
Source File: SpringWebFluxTest.java    From java-specialagent with 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 #14
Source File: ApplicationConfigurationMetadataResolverAutoConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: RestTemplateWithTimeoutConfig.java    From hellokoding-courses with MIT License 5 votes vote down vote up
@Bean
RestTemplate restTemplateWithConnectReadTimeout() {
    return new RestTemplateBuilder()
        .setConnectTimeout(Duration.ofMillis(TIMEOUT))
        .setReadTimeout(Duration.ofMillis(TIMEOUT))
        .build();
}
 
Example #16
Source File: RestTemplateConfig.java    From sfg-blog-posts with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public RestTemplate restTemplate() {
  return new RestTemplateBuilder()
          .requestFactory(this::clientHttpRequestFactory)
          .errorHandler(new CustomClientErrorHandler())
          .interceptors(new CustomClientHttpRequestInterceptor())
          .build();
}
 
Example #17
Source File: GithubService.java    From github-release-notes-generator with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with 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 #19
Source File: GeneratorServiceApplicationStart.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 实例化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 #20
Source File: GitHub.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param templateBuilder
 * @param logger
 * @param properties
 */
public GitHub(@Qualifier("tracker") RestTemplateBuilder templateBuilder, Logger logger, GitHubProperties properties) {

	this.operations = templateBuilder.uriTemplateHandler(new DefaultUriBuilderFactory(properties.getApiUrl())).build();
	this.logger = logger;
	this.properties = properties;
}
 
Example #21
Source File: RestTemplateConfig.java    From servicecomb-pack with 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 #22
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with 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 #23
Source File: ApiApplicationStart.java    From MicroCommunity with 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 #24
Source File: SpringBootAdminClientAutoConfiguration.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: ProjectGenerationStatPublisherTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: LinkSMSConfig.java    From sms with MIT License 5 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
	return builder
			.rootUri(baseUrl)
			.messageConverters(formHttpMessageConverter(), stringHttpMessageConverter())
			.build();
}
 
Example #27
Source File: RestTemplateConfig.java    From springbootexamples with 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 #28
Source File: RestTemplateConfig.java    From springbootexamples with 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 #29
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with 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 #30
Source File: ProjectGenerationStatPublisher.java    From initializr with 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;
}