Commit c973488c authored by Stephane Nicoll's avatar Stephane Nicoll

Merge pull request #12707 from nosan:feature/web-service-template

* pr/12707:
  Polish "Add auto-configuration for WebServiceTemplate"
  Extract ClientHttpRequestFactory detection to its own class
  Add auto-configuration for WebServiceTemplate
parents 283ceaa0 8bcea0d8
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.webservices.client;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.webservices.client.WebServiceTemplateBuilder;
import org.springframework.boot.webservices.client.WebServiceTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.util.CollectionUtils;
import org.springframework.ws.client.core.WebServiceTemplate;
/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link WebServiceTemplate}.
*
* @author Dmytro Nosan
* @since 2.1.0
*/
@Configuration
@ConditionalOnClass({ WebServiceTemplate.class, Unmarshaller.class, Marshaller.class })
public class WebServiceTemplateAutoConfiguration {
private final ObjectProvider<List<WebServiceTemplateCustomizer>> webServiceTemplateCustomizers;
public WebServiceTemplateAutoConfiguration(
ObjectProvider<List<WebServiceTemplateCustomizer>> webServiceTemplateCustomizers) {
this.webServiceTemplateCustomizers = webServiceTemplateCustomizers;
}
@Bean
@ConditionalOnMissingBean
public WebServiceTemplateBuilder webServiceTemplateBuilder() {
WebServiceTemplateBuilder builder = new WebServiceTemplateBuilder();
List<WebServiceTemplateCustomizer> customizers = this.webServiceTemplateCustomizers
.getIfAvailable();
if (!CollectionUtils.isEmpty(customizers)) {
customizers = new ArrayList<>(customizers);
AnnotationAwareOrderComparator.sort(customizers);
builder = builder.customizers(customizers);
}
return builder;
}
}
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Auto-configuration for Spring Web Services Clients.
*/
package org.springframework.boot.autoconfigure.webservices.client;
...@@ -126,7 +126,8 @@ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ ...@@ -126,7 +126,8 @@ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
# Failure analyzers # Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\ org.springframework.boot.diagnostics.FailureAnalyzer=\
......
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.webservices.client;
import java.util.function.Consumer;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.boot.webservices.client.WebServiceTemplateBuilder;
import org.springframework.boot.webservices.client.WebServiceTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.ws.transport.http.ClientHttpRequestMessageSender;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link WebServiceTemplateAutoConfiguration}.
*
* @author Stephane Nicoll
* @author Dmytro Nosan
*/
public class WebServiceTemplateAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class));
@Test
public void autoConfiguredBuilderShouldNotHaveMarshallerAndUnmarshaller() {
this.contextRunner.run(assertWebServiceTemplateBuilder((builder) -> {
WebServiceTemplate webServiceTemplate = builder.build();
assertThat(webServiceTemplate.getUnmarshaller()).isNull();
assertThat(webServiceTemplate.getMarshaller()).isNull();
}));
}
@Test
public void autoConfiguredBuilderShouldHaveHttpMessageSenderByDefault() {
this.contextRunner.run(assertWebServiceTemplateBuilder((builder) -> {
WebServiceTemplate webServiceTemplate = builder.build();
assertThat(webServiceTemplate.getMessageSenders()).hasSize(1);
WebServiceMessageSender messageSender = webServiceTemplate
.getMessageSenders()[0];
assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class);
}));
}
@Test
public void webServiceTemplateWhenHasCustomBuilderShouldUseCustomBuilder() {
this.contextRunner
.withUserConfiguration(CustomWebServiceTemplateBuilderConfig.class)
.run(assertWebServiceTemplateBuilder((builder) -> {
WebServiceTemplate webServiceTemplate = builder.build();
assertThat(webServiceTemplate.getMarshaller())
.isSameAs(CustomWebServiceTemplateBuilderConfig.marshaller);
}));
}
@Test
public void webServiceTemplateShouldApplyCustomizer() {
this.contextRunner.withUserConfiguration(WebServiceTemplateCustomizerConfig.class)
.run(assertWebServiceTemplateBuilder((builder) -> {
WebServiceTemplate webServiceTemplate = builder.build();
assertThat(webServiceTemplate.getUnmarshaller())
.isSameAs(WebServiceTemplateCustomizerConfig.unmarshaller);
}));
}
@Test
public void builderShouldBeFreshForEachUse() {
this.contextRunner.withUserConfiguration(DirtyWebServiceTemplateConfig.class)
.run((context) -> {
assertThat(context).hasNotFailed();
});
}
private ContextConsumer<AssertableApplicationContext> assertWebServiceTemplateBuilder(
Consumer<WebServiceTemplateBuilder> builder) {
return (context) -> {
assertThat(context).hasSingleBean(WebServiceTemplateBuilder.class);
builder.accept(context.getBean(WebServiceTemplateBuilder.class));
};
}
@Configuration
static class DirtyWebServiceTemplateConfig {
@Bean
public WebServiceTemplate webServiceTemplateOne(
WebServiceTemplateBuilder builder) {
try {
return builder.build();
}
finally {
breakBuilderOnNextCall(builder);
}
}
@Bean
public WebServiceTemplate webServiceTemplateTwo(
WebServiceTemplateBuilder builder) {
try {
return builder.build();
}
finally {
breakBuilderOnNextCall(builder);
}
}
private void breakBuilderOnNextCall(WebServiceTemplateBuilder builder) {
builder.additionalCustomizers((webServiceTemplate) -> {
throw new IllegalStateException();
});
}
}
@Configuration
static class CustomWebServiceTemplateBuilderConfig {
private static final Marshaller marshaller = new Jaxb2Marshaller();
@Bean
public WebServiceTemplateBuilder webServiceTemplateBuilder() {
return new WebServiceTemplateBuilder().setMarshaller(marshaller);
}
}
@Configuration
static class WebServiceTemplateCustomizerConfig {
private static final Unmarshaller unmarshaller = new Jaxb2Marshaller();
@Bean
public WebServiceTemplateCustomizer webServiceTemplateCustomizer() {
return (ws) -> ws.setUnmarshaller(unmarshaller);
}
}
}
...@@ -7388,6 +7388,51 @@ following example: ...@@ -7388,6 +7388,51 @@ following example:
[[boot-features-webservices-template]]
== Calling Web Services with `WebServiceTemplate`
If you need to call remote Web services from your application, you can use the
{spring-webservices-reference}#client-web-service-template[`WebServiceTemplate`] class.
Since `WebServiceTemplate` instances often need to be customized before being used, Spring
Boot does not provide any single auto-configured `WebServiceTemplate` bean. It does,
however, auto-configure a `WebServiceTemplateBuilder`, which can be used to create
`WebServiceTemplate` instances when needed.
The following code shows a typical example:
[source,java,indent=0]
----
@Service
public class MyService {
private final WebServiceTemplate webServiceTemplate;
public MyService(WebServiceTemplateBuilder webServiceTemplateBuilder) {
this.webServiceTemplate = webServiceTemplateBuilder.build();
}
public DetailsResp someWsCall(DetailsReq detailsReq) {
return (DetailsResp) this.webServiceTemplate.marshalSendAndReceive(detailsReq, new SoapActionCallback(ACTION));
}
}
----
By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based
`WebServiceMessageSender` using the available HTTP client libraries on the classpath. You
can also customize read and connection timeouts as follows:
[source,java,indent=0]
----
@Bean
public WebServiceTemplate webServiceTemplate(WebServiceTemplateBuilder builder) {
return builder.messageSenders(new HttpWebServiceMessageSenderBuilder()
.setReadTimeout(5000).setConnectionTimeout(2000).build()).build();
}
----
[[boot-features-developing-auto-configuration]] [[boot-features-developing-auto-configuration]]
== Creating Your Own Auto-configuration == Creating Your Own Auto-configuration
If you work in a company that develops shared libraries, or if you work on an open-source If you work in a company that develops shared libraries, or if you work on an open-source
......
...@@ -245,6 +245,11 @@ ...@@ -245,6 +245,11 @@
<artifactId>spring-orm</artifactId> <artifactId>spring-orm</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId> <artifactId>spring-test</artifactId>
...@@ -270,6 +275,11 @@ ...@@ -270,6 +275,11 @@
<artifactId>spring-security-web</artifactId> <artifactId>spring-security-web</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>org.yaml</groupId> <groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId> <artifactId>snakeyaml</artifactId>
......
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.client;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import org.springframework.beans.BeanUtils;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.ClassUtils;
/**
* A supplier for {@link ClientHttpRequestFactory} that detects the preferred candidate
* based on the available implementations on the classpath.
*
* @author Stephane Nicoll
* @since 2.1.0
*/
public class ClientHttpRequestFactorySupplier
implements Supplier<ClientHttpRequestFactory> {
private static final Map<String, String> REQUEST_FACTORY_CANDIDATES;
static {
Map<String, String> candidates = new LinkedHashMap<>();
candidates.put("org.apache.http.client.HttpClient",
"org.springframework.http.client.HttpComponentsClientHttpRequestFactory");
candidates.put("okhttp3.OkHttpClient",
"org.springframework.http.client.OkHttp3ClientHttpRequestFactory");
REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates);
}
@Override
public ClientHttpRequestFactory get() {
for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES
.entrySet()) {
ClassLoader classLoader = getClass().getClassLoader();
if (ClassUtils.isPresent(candidate.getKey(), classLoader)) {
Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(),
classLoader);
return (ClientHttpRequestFactory) BeanUtils
.instantiateClass(factoryClass);
}
}
return new SimpleClientHttpRequestFactory();
}
}
...@@ -23,9 +23,7 @@ import java.util.ArrayList; ...@@ -23,9 +23,7 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier; import java.util.function.Supplier;
...@@ -33,11 +31,9 @@ import org.springframework.beans.BeanUtils; ...@@ -33,11 +31,9 @@ import org.springframework.beans.BeanUtils;
import org.springframework.http.client.AbstractClientHttpRequestFactoryWrapper; import org.springframework.http.client.AbstractClientHttpRequestFactoryWrapper;
import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthorizationInterceptor; import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.ResponseErrorHandler;
...@@ -64,17 +60,6 @@ import org.springframework.web.util.UriTemplateHandler; ...@@ -64,17 +60,6 @@ import org.springframework.web.util.UriTemplateHandler;
*/ */
public class RestTemplateBuilder { public class RestTemplateBuilder {
private static final Map<String, String> REQUEST_FACTORY_CANDIDATES;
static {
Map<String, String> candidates = new LinkedHashMap<>();
candidates.put("org.apache.http.client.HttpClient",
"org.springframework.http.client.HttpComponentsClientHttpRequestFactory");
candidates.put("okhttp3.OkHttpClient",
"org.springframework.http.client.OkHttp3ClientHttpRequestFactory");
REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates);
}
private final boolean detectRequestFactory; private final boolean detectRequestFactory;
private final String rootUri; private final String rootUri;
...@@ -561,7 +546,7 @@ public class RestTemplateBuilder { ...@@ -561,7 +546,7 @@ public class RestTemplateBuilder {
requestFactory = this.requestFactorySupplier.get(); requestFactory = this.requestFactorySupplier.get();
} }
else if (this.detectRequestFactory) { else if (this.detectRequestFactory) {
requestFactory = detectRequestFactory(); requestFactory = new ClientHttpRequestFactorySupplier().get();
} }
if (requestFactory != null) { if (requestFactory != null) {
ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary( ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary(
...@@ -590,20 +575,6 @@ public class RestTemplateBuilder { ...@@ -590,20 +575,6 @@ public class RestTemplateBuilder {
return unwrappedRequestFactory; return unwrappedRequestFactory;
} }
private ClientHttpRequestFactory detectRequestFactory() {
for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES
.entrySet()) {
ClassLoader classLoader = getClass().getClassLoader();
if (ClassUtils.isPresent(candidate.getKey(), classLoader)) {
Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(),
classLoader);
return (ClientHttpRequestFactory) BeanUtils
.instantiateClass(factoryClass);
}
}
return new SimpleClientHttpRequestFactory();
}
private <T> Set<T> append(Set<T> set, T addition) { private <T> Set<T> append(Set<T> set, T addition) {
Set<T> result = new LinkedHashSet<>(set != null ? set : Collections.emptySet()); Set<T> result = new LinkedHashSet<>(set != null ? set : Collections.emptySet());
result.add(addition); result.add(addition);
......
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.webservices.client;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import org.springframework.boot.web.client.ClientHttpRequestFactorySupplier;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.ws.transport.http.ClientHttpRequestMessageSender;
/**
* {@link WebServiceMessageSender} builder that can detect a suitable HTTP library based
* on the classpath.
*
* @author Stephane Nicoll
* @since 2.1.0
*/
public class HttpWebServiceMessageSenderBuilder {
private Integer connectionTimeout;
private Integer readTimeout;
private Supplier<ClientHttpRequestFactory> requestFactorySupplier;
/**
* Set the connection timeout in milliseconds.
* @param connectionTimeout the connection timeout in milliseconds
* @return a new builder instance
*/
public HttpWebServiceMessageSenderBuilder setConnectionTimeout(
int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
/**
* Set the read timeout in milliseconds.
* @param readTimeout the read timeout in milliseconds
* @return a new builder instance
*/
public HttpWebServiceMessageSenderBuilder setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Set the {@code Supplier} of {@link ClientHttpRequestFactory} that should be called
* to create the HTTP-based {@link WebServiceMessageSender}.
* @param requestFactorySupplier the supplier for the request factory
* @return a new builder instance
*/
public HttpWebServiceMessageSenderBuilder requestFactory(
Supplier<ClientHttpRequestFactory> requestFactorySupplier) {
Assert.notNull(requestFactorySupplier,
"RequestFactory Supplier must not be null");
this.requestFactorySupplier = requestFactorySupplier;
return this;
}
public WebServiceMessageSender build() {
ClientHttpRequestFactory requestFactory = (this.requestFactorySupplier != null
? this.requestFactorySupplier.get()
: new ClientHttpRequestFactorySupplier().get());
if (this.connectionTimeout != null) {
new TimeoutRequestFactoryCustomizer(this.connectionTimeout,
"setConnectTimeout").customize(requestFactory);
}
if (this.readTimeout != null) {
new TimeoutRequestFactoryCustomizer(this.readTimeout, "setReadTimeout")
.customize(requestFactory);
}
return new ClientHttpRequestMessageSender(requestFactory);
}
/**
* {@link ClientHttpRequestFactory} customizer to call a "set timeout" method.
*/
private static class TimeoutRequestFactoryCustomizer {
private final int timeout;
private final String methodName;
TimeoutRequestFactoryCustomizer(int timeout, String methodName) {
this.timeout = timeout;
this.methodName = methodName;
}
public void customize(ClientHttpRequestFactory factory) {
ReflectionUtils.invokeMethod(findMethod(factory), factory, this.timeout);
}
private Method findMethod(ClientHttpRequestFactory factory) {
Method method = ReflectionUtils.findMethod(factory.getClass(),
this.methodName, int.class);
if (method != null) {
return method;
}
throw new IllegalStateException("Request factory " + factory.getClass()
+ " does not have a " + this.methodName + "(int) method");
}
}
}
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.webservices.client;
import org.springframework.ws.client.core.WebServiceTemplate;
/**
* Callback interface that can be used to customize a {@link WebServiceTemplate}.
*
* @author Dmytro Nosan
* @since 2.1.0
*/
public interface WebServiceTemplateCustomizer {
/**
* Callback to customize a {@link WebServiceTemplate} instance.
* @param webServiceTemplate the template to customize
*/
void customize(WebServiceTemplate webServiceTemplate);
}
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Web Services client utilities.
*/
package org.springframework.boot.webservices.client;
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.webservices.client;
import okhttp3.OkHttpClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.ws.transport.http.ClientHttpRequestMessageSender;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link HttpWebServiceMessageSenderBuilder} when Http Components is not
* available.
*
* @author Stephane Nicoll
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions("httpclient-*.jar")
public class HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests {
private final HttpWebServiceMessageSenderBuilder builder = new HttpWebServiceMessageSenderBuilder();
@Test
public void buildUseOkHttp3ByDefault() {
WebServiceMessageSender messageSender = this.builder.build();
assertOkHttp3RequestFactory(messageSender);
}
@Test
public void buildWithCustomTimeouts() {
WebServiceMessageSender messageSender = this.builder.setConnectionTimeout(5000)
.setReadTimeout(2000).build();
OkHttp3ClientHttpRequestFactory factory = assertOkHttp3RequestFactory(
messageSender);
OkHttpClient client = (OkHttpClient) ReflectionTestUtils.getField(factory,
"client");
assertThat(client).isNotNull();
assertThat(client.connectTimeoutMillis()).isEqualTo(5000);
assertThat(client.readTimeoutMillis()).isEqualTo(2000);
}
private OkHttp3ClientHttpRequestFactory assertOkHttp3RequestFactory(
WebServiceMessageSender messageSender) {
assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class);
ClientHttpRequestMessageSender sender = (ClientHttpRequestMessageSender) messageSender;
ClientHttpRequestFactory requestFactory = sender.getRequestFactory();
assertThat(requestFactory).isInstanceOf(OkHttp3ClientHttpRequestFactory.class);
return (OkHttp3ClientHttpRequestFactory) requestFactory;
}
}
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.webservices.client;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.ws.transport.http.ClientHttpRequestMessageSender;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link HttpWebServiceMessageSenderBuilder} when no preferred HTTP clients are
* available
*
* @author Stephane Nicoll
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "httpclient-*.jar", "okhttp*.jar" })
public class HttpWebServiceMessageSenderBuilderSimpleIntegrationTests {
private final HttpWebServiceMessageSenderBuilder builder = new HttpWebServiceMessageSenderBuilder();
@Test
public void buildUseUseSimpleClientByDefault() {
WebServiceMessageSender messageSender = this.builder.build();
assertSimpleClientRequestFactory(messageSender);
}
@Test
public void buildWithCustomTimeouts() {
WebServiceMessageSender messageSender = this.builder.setConnectionTimeout(5000)
.setReadTimeout(2000).build();
SimpleClientHttpRequestFactory requestFactory = assertSimpleClientRequestFactory(
messageSender);
assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout"))
.isEqualTo(5000);
assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout"))
.isEqualTo(2000);
}
private SimpleClientHttpRequestFactory assertSimpleClientRequestFactory(
WebServiceMessageSender messageSender) {
assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class);
ClientHttpRequestMessageSender sender = (ClientHttpRequestMessageSender) messageSender;
ClientHttpRequestFactory requestFactory = sender.getRequestFactory();
assertThat(requestFactory).isInstanceOf(SimpleClientHttpRequestFactory.class);
return (SimpleClientHttpRequestFactory) requestFactory;
}
}
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.webservices.client;
import org.apache.http.client.config.RequestConfig;
import org.junit.Test;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.ws.transport.http.ClientHttpRequestMessageSender;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link HttpWebServiceMessageSenderBuilder}.
*
* @author Stephane Nicoll
*/
public class HttpWebServiceMessageSenderBuilderTests {
@Test
public void buildWithRequestFactorySupplier() {
ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class);
ClientHttpRequestMessageSender messageSender = build(
new HttpWebServiceMessageSenderBuilder()
.requestFactory(() -> requestFactory));
assertThat(messageSender.getRequestFactory()).isSameAs(requestFactory);
}
@Test
public void buildWithReadAndConnectTimeout() {
ClientHttpRequestMessageSender messageSender = build(
new HttpWebServiceMessageSenderBuilder()
.requestFactory(SimpleClientHttpRequestFactory::new)
.setConnectionTimeout(5000).setReadTimeout(2000));
SimpleClientHttpRequestFactory requestFactory = (SimpleClientHttpRequestFactory) messageSender
.getRequestFactory();
assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout"))
.isEqualTo(5000);
assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout"))
.isEqualTo(2000);
}
@Test
public void buildUsesHttpComponentsBydefault() {
ClientHttpRequestMessageSender messageSender = build(
new HttpWebServiceMessageSenderBuilder().setConnectionTimeout(5000)
.setReadTimeout(2000));
ClientHttpRequestFactory requestFactory = messageSender.getRequestFactory();
assertThat(requestFactory)
.isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
RequestConfig requestConfig = (RequestConfig) ReflectionTestUtils
.getField(requestFactory, "requestConfig");
assertThat(requestConfig).isNotNull();
assertThat(requestConfig.getConnectTimeout()).isEqualTo(5000);
assertThat(requestConfig.getSocketTimeout()).isEqualTo(2000);
}
private ClientHttpRequestMessageSender build(
HttpWebServiceMessageSenderBuilder builder) {
WebServiceMessageSender messageSender = builder.build();
assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class);
return ((ClientHttpRequestMessageSender) messageSender);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment