001package io.freefair.spring.okhttp;
002
003import okhttp3.OkHttpClient;
004import org.springframework.boot.autoconfigure.AutoConfiguration;
005import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
006import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
007import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
008import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
009import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
010import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
011import org.springframework.boot.autoconfigure.web.client.RestTemplateBuilderConfigurer;
012import org.springframework.boot.web.client.RestTemplateBuilder;
013import org.springframework.boot.web.client.RestTemplateCustomizer;
014import org.springframework.context.annotation.Bean;
015import org.springframework.context.annotation.Conditional;
016import org.springframework.context.annotation.Lazy;
017import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
018import org.springframework.web.client.RestTemplate;
019
020/**
021 * @author Lars Grefer
022 * @see RestTemplateAutoConfiguration
023 */
024@AutoConfiguration(before = RestTemplateAutoConfiguration.class, after = HttpMessageConvertersAutoConfiguration.class)
025@ConditionalOnClass({RestTemplateCustomizer.class, RestTemplate.class})
026@Conditional(OkHttpRestTemplateAutoConfiguration.NotReactiveWebApplicationCondition.class)
027public class OkHttpRestTemplateAutoConfiguration {
028
029    @Bean
030    @Lazy
031    @ConditionalOnMissingBean
032    public RestTemplateBuilder restTemplateBuilder(RestTemplateBuilderConfigurer restTemplateBuilderConfigurer,
033                                                   OkHttpClient okHttpClient) {
034        RestTemplateBuilder builder = new RestTemplateBuilder();
035        builder = builder.requestFactory(() -> new OkHttp3ClientHttpRequestFactory(okHttpClient));
036        return restTemplateBuilderConfigurer.configure(builder);
037    }
038
039    static class NotReactiveWebApplicationCondition extends NoneNestedConditions {
040
041        NotReactiveWebApplicationCondition() {
042            super(ConfigurationPhase.PARSE_CONFIGURATION);
043        }
044
045        @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
046        private static class ReactiveWebApplication {
047
048        }
049
050    }
051
052}