Commit 2a592103 authored by Phillip Webb's avatar Phillip Webb

Polish formatting

parent 91a7bf92
...@@ -115,8 +115,7 @@ public class EndpointWebMvcAutoConfigurationTests { ...@@ -115,8 +115,7 @@ public class EndpointWebMvcAutoConfigurationTests {
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();
private final AnnotationConfigEmbeddedWebApplicationContext applicationContext = private final AnnotationConfigEmbeddedWebApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext();
new AnnotationConfigEmbeddedWebApplicationContext();
private static ThreadLocal<Ports> ports = new ThreadLocal<Ports>(); private static ThreadLocal<Ports> ports = new ThreadLocal<Ports>();
...@@ -125,10 +124,8 @@ public class EndpointWebMvcAutoConfigurationTests { ...@@ -125,10 +124,8 @@ public class EndpointWebMvcAutoConfigurationTests {
Ports values = new Ports(); Ports values = new Ports();
ports.set(values); ports.set(values);
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext,
"management.context-path=", "management.context-path=", "management.security.enabled=false",
"management.security.enabled=false", "server.servlet.context-path=", "server.port=" + ports.get().server);
"server.servlet.context-path=",
"server.port=" + ports.get().server);
} }
@After @After
...@@ -276,8 +273,8 @@ public class EndpointWebMvcAutoConfigurationTests { ...@@ -276,8 +273,8 @@ public class EndpointWebMvcAutoConfigurationTests {
@Test @Test
public void onRandomPort() throws Exception { public void onRandomPort() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.port=0",
"management.port=0", "management.security.enabled=false"); "management.security.enabled=false");
this.applicationContext.register(RootConfig.class, EndpointConfig.class, this.applicationContext.register(RootConfig.class, EndpointConfig.class,
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ErrorMvcAutoConfiguration.class); ErrorMvcAutoConfiguration.class);
...@@ -565,8 +562,8 @@ public class EndpointWebMvcAutoConfigurationTests { ...@@ -565,8 +562,8 @@ public class EndpointWebMvcAutoConfigurationTests {
@Test @Test
public void managementServerCanDisableSslWhenUsingADifferentPort() throws Exception { public void managementServerCanDisableSslWhenUsingADifferentPort() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext,
"management.port=" + ports.get().management, "management.port=" + ports.get().management, "server.ssl.enabled=true",
"server.ssl.enabled=true", "server.ssl.key-store=classpath:test.jks", "server.ssl.key-store=classpath:test.jks",
"server.ssl.key-password=password", "management.ssl.enabled=false"); "server.ssl.key-password=password", "management.ssl.enabled=false");
this.applicationContext.register(RootConfig.class, EndpointConfig.class, this.applicationContext.register(RootConfig.class, EndpointConfig.class,
...@@ -652,8 +649,7 @@ public class EndpointWebMvcAutoConfigurationTests { ...@@ -652,8 +649,7 @@ public class EndpointWebMvcAutoConfigurationTests {
private void endpointEnabledOverride(String name, Class<? extends MvcEndpoint> type) private void endpointEnabledOverride(String name, Class<? extends MvcEndpoint> type)
throws Exception { throws Exception {
this.applicationContext.register(LoggingConfig.class, RootConfig.class, this.applicationContext.register(LoggingConfig.class, RootConfig.class,
BaseConfiguration.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class);
EndpointWebMvcAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext,
"endpoints.enabled:false", "endpoints.enabled:false",
String.format("endpoints_%s_enabled:true", name)); String.format("endpoints_%s_enabled:true", name));
...@@ -736,7 +732,7 @@ public class EndpointWebMvcAutoConfigurationTests { ...@@ -736,7 +732,7 @@ public class EndpointWebMvcAutoConfigurationTests {
} }
@Configuration @Configuration
@Import({PropertyPlaceholderAutoConfiguration.class, @Import({ PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class,
JacksonAutoConfiguration.class, EndpointAutoConfiguration.class, JacksonAutoConfiguration.class, EndpointAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
......
...@@ -57,8 +57,8 @@ class HazelcastCacheConfiguration { ...@@ -57,8 +57,8 @@ class HazelcastCacheConfiguration {
} }
@Bean @Bean
public HazelcastCacheManager cacheManager( public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance)
HazelcastInstance existingHazelcastInstance) throws IOException { throws IOException {
HazelcastCacheManager cacheManager = new HazelcastCacheManager( HazelcastCacheManager cacheManager = new HazelcastCacheManager(
existingHazelcastInstance); existingHazelcastInstance);
return this.customizers.customize(cacheManager); return this.customizers.customize(cacheManager);
......
...@@ -81,12 +81,12 @@ class OnWebApplicationCondition extends SpringBootCondition { ...@@ -81,12 +81,12 @@ class OnWebApplicationCondition extends SpringBootCondition {
return new ConditionOutcome(reactiveOutcome.isMatch(), return new ConditionOutcome(reactiveOutcome.isMatch(),
message.because(reactiveOutcome.getMessage())); message.because(reactiveOutcome.getMessage()));
} }
boolean finalOutcome = (required ? boolean finalOutcome = (required
servletOutcome.isMatch() && reactiveOutcome.isMatch() : ? servletOutcome.isMatch() && reactiveOutcome.isMatch()
servletOutcome.isMatch() || reactiveOutcome.isMatch()); : servletOutcome.isMatch() || reactiveOutcome.isMatch());
return new ConditionOutcome(finalOutcome, message.because( return new ConditionOutcome(finalOutcome,
servletOutcome.getMessage()).append("and").append( message.because(servletOutcome.getMessage()).append("and")
reactiveOutcome.getMessage())); .append(reactiveOutcome.getMessage()));
} }
} }
...@@ -115,16 +115,16 @@ class OnWebApplicationCondition extends SpringBootCondition { ...@@ -115,16 +115,16 @@ class OnWebApplicationCondition extends SpringBootCondition {
private ConditionOutcome isReactiveWebApplication(ConditionContext context) { private ConditionOutcome isReactiveWebApplication(ConditionContext context) {
ConditionMessage.Builder message = ConditionMessage.forCondition(""); ConditionMessage.Builder message = ConditionMessage.forCondition("");
if (context.getResourceLoader() instanceof ReactiveWebApplicationContext) { if (context.getResourceLoader() instanceof ReactiveWebApplicationContext) {
return ConditionOutcome.match( return ConditionOutcome
message.foundExactly("ReactiveWebApplicationContext")); .match(message.foundExactly("ReactiveWebApplicationContext"));
} }
return ConditionOutcome.noMatch(message.because( return ConditionOutcome
"not a reactive web application")); .noMatch(message.because("not a reactive web application"));
} }
private Type deduceType(AnnotatedTypeMetadata metadata) { private Type deduceType(AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes( Map<String, Object> attributes = metadata
ConditionalOnWebApplication.class.getName()); .getAnnotationAttributes(ConditionalOnWebApplication.class.getName());
if (attributes != null) { if (attributes != null) {
return (Type) attributes.get("type"); return (Type) attributes.get("type");
} }
......
...@@ -31,8 +31,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi ...@@ -31,8 +31,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Mark Paluch * @author Mark Paluch
* @since 2.0.0 * @since 2.0.0
*/ */
class ReactiveMongoRepositoriesAutoConfigureRegistrar extends class ReactiveMongoRepositoriesAutoConfigureRegistrar
AbstractRepositoryConfigurationSourceSupport { extends AbstractRepositoryConfigurationSourceSupport {
@Override @Override
protected Class<? extends Annotation> getAnnotation() { protected Class<? extends Annotation> getAnnotation() {
......
...@@ -34,8 +34,8 @@ import org.springframework.data.mongodb.core.ReactiveMongoClientFactoryBean; ...@@ -34,8 +34,8 @@ import org.springframework.data.mongodb.core.ReactiveMongoClientFactoryBean;
* @since 2.0.0 * @since 2.0.0
*/ */
@Order(Ordered.LOWEST_PRECEDENCE) @Order(Ordered.LOWEST_PRECEDENCE)
public class ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor extends public class ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor
AbstractDependsOnBeanFactoryPostProcessor { extends AbstractDependsOnBeanFactoryPostProcessor {
public ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor( public ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor(
String... dependsOn) { String... dependsOn) {
......
...@@ -45,6 +45,7 @@ import org.springframework.core.env.Environment; ...@@ -45,6 +45,7 @@ import org.springframework.core.env.Environment;
public class MongoClientFactory { public class MongoClientFactory {
private final MongoProperties properties; private final MongoProperties properties;
private final Environment environment; private final Environment environment;
public MongoClientFactory(MongoProperties properties, Environment environment) { public MongoClientFactory(MongoProperties properties, Environment environment) {
...@@ -54,8 +55,8 @@ public class MongoClientFactory { ...@@ -54,8 +55,8 @@ public class MongoClientFactory {
/** /**
* Creates a {@link MongoClient} using the given {@code options}. If the environment * Creates a {@link MongoClient} using the given {@code options}. If the environment
* contains a {@code local.mongo.port} property, it is used to configure a client * contains a {@code local.mongo.port} property, it is used to configure a client to
* to an embedded MongoDB instance. * an embedded MongoDB instance.
* @param options the options * @param options the options
* @return the Mongo client * @return the Mongo client
*/ */
...@@ -83,8 +84,7 @@ public class MongoClientFactory { ...@@ -83,8 +84,7 @@ public class MongoClientFactory {
} }
String host = this.properties.getHost() == null ? "localhost" String host = this.properties.getHost() == null ? "localhost"
: this.properties.getHost(); : this.properties.getHost();
return new MongoClient( return new MongoClient(Collections.singletonList(new ServerAddress(host, port)),
Collections.singletonList(new ServerAddress(host, port)),
Collections.emptyList(), options); Collections.emptyList(), options);
} }
...@@ -100,24 +100,24 @@ public class MongoClientFactory { ...@@ -100,24 +100,24 @@ public class MongoClientFactory {
} }
List<MongoCredential> credentials = new ArrayList<MongoCredential>(); List<MongoCredential> credentials = new ArrayList<MongoCredential>();
if (hasCustomCredentials()) { if (hasCustomCredentials()) {
String database = this.properties.getAuthenticationDatabase() == null ? this.properties String database = this.properties.getAuthenticationDatabase() == null
.getMongoClientDatabase() : this.properties ? this.properties.getMongoClientDatabase()
.getAuthenticationDatabase(); : this.properties.getAuthenticationDatabase();
credentials.add(MongoCredential.createCredential( credentials.add(
this.properties.getUsername(), database, MongoCredential.createCredential(this.properties.getUsername(),
this.properties.getPassword())); database, this.properties.getPassword()));
} }
String host = this.properties.getHost() == null ? "localhost" String host = this.properties.getHost() == null ? "localhost"
: this.properties.getHost(); : this.properties.getHost();
int port = this.properties.getPort() != null ? this.properties.getPort() int port = this.properties.getPort() != null ? this.properties.getPort()
: MongoProperties.DEFAULT_PORT; : MongoProperties.DEFAULT_PORT;
return new MongoClient( return new MongoClient(
Collections.singletonList(new ServerAddress(host, port)), Collections.singletonList(new ServerAddress(host, port)), credentials,
credentials, options); options);
} }
// The options and credentials are in the URI // The options and credentials are in the URI
return new MongoClient(new MongoClientURI(this.properties.determineUri(), return new MongoClient(
builder(options))); new MongoClientURI(this.properties.determineUri(), builder(options)));
} }
private boolean hasCustomAddress() { private boolean hasCustomAddress() {
......
...@@ -56,8 +56,8 @@ public class ReactiveMongoClientFactory { ...@@ -56,8 +56,8 @@ public class ReactiveMongoClientFactory {
/** /**
* Creates a {@link MongoClient} using the given {@code settings}. If the environment * Creates a {@link MongoClient} using the given {@code settings}. If the environment
* contains a {@code local.mongo.port} property, it is used to configure a client * contains a {@code local.mongo.port} property, it is used to configure a client to
* to an embedded MongoDB instance. * an embedded MongoDB instance.
* @param settings the settings * @param settings the settings
* @return the Mongo client * @return the Mongo client
*/ */
...@@ -85,8 +85,7 @@ public class ReactiveMongoClientFactory { ...@@ -85,8 +85,7 @@ public class ReactiveMongoClientFactory {
String host = this.properties.getHost() == null ? "localhost" String host = this.properties.getHost() == null ? "localhost"
: this.properties.getHost(); : this.properties.getHost();
ClusterSettings clusterSettings = ClusterSettings.builder() ClusterSettings clusterSettings = ClusterSettings.builder()
.hosts(Collections.singletonList(new ServerAddress(host, port))) .hosts(Collections.singletonList(new ServerAddress(host, port))).build();
.build();
builder.clusterSettings(clusterSettings); builder.clusterSettings(clusterSettings);
return MongoClients.create(builder.build()); return MongoClients.create(builder.build());
} }
...@@ -101,12 +100,12 @@ public class ReactiveMongoClientFactory { ...@@ -101,12 +100,12 @@ public class ReactiveMongoClientFactory {
Builder builder = builder(settings); Builder builder = builder(settings);
if (hasCustomCredentials()) { if (hasCustomCredentials()) {
List<MongoCredential> credentials = new ArrayList<MongoCredential>(); List<MongoCredential> credentials = new ArrayList<MongoCredential>();
String database = this.properties.getAuthenticationDatabase() == null ? this.properties String database = this.properties.getAuthenticationDatabase() == null
.getMongoClientDatabase() : this.properties ? this.properties.getMongoClientDatabase()
.getAuthenticationDatabase(); : this.properties.getAuthenticationDatabase();
credentials.add(MongoCredential.createCredential( credentials.add(
this.properties.getUsername(), database, MongoCredential.createCredential(this.properties.getUsername(),
this.properties.getPassword())); database, this.properties.getPassword()));
builder.credentialList(credentials); builder.credentialList(credentials);
} }
String host = this.properties.getHost() == null ? "localhost" String host = this.properties.getHost() == null ? "localhost"
...@@ -127,22 +126,17 @@ public class ReactiveMongoClientFactory { ...@@ -127,22 +126,17 @@ public class ReactiveMongoClientFactory {
private Builder createBuilder(MongoClientSettings settings, private Builder createBuilder(MongoClientSettings settings,
ConnectionString connectionString) { ConnectionString connectionString) {
Builder builder = builder(settings) Builder builder = builder(settings)
.clusterSettings( .clusterSettings(ClusterSettings.builder()
ClusterSettings.builder().applyConnectionString(connectionString) .applyConnectionString(connectionString).build())
.build()) .connectionPoolSettings(ConnectionPoolSettings.builder()
.connectionPoolSettings( .applyConnectionString(connectionString).build())
ConnectionPoolSettings.builder() .serverSettings(ServerSettings.builder()
.applyConnectionString(connectionString).build()) .applyConnectionString(connectionString).build())
.serverSettings(
ServerSettings.builder().applyConnectionString(connectionString)
.build())
.credentialList(connectionString.getCredentialList()) .credentialList(connectionString.getCredentialList())
.sslSettings( .sslSettings(SslSettings.builder().applyConnectionString(connectionString)
SslSettings.builder().applyConnectionString(connectionString)
.build()) .build())
.socketSettings( .socketSettings(SocketSettings.builder()
SocketSettings.builder().applyConnectionString(connectionString) .applyConnectionString(connectionString).build());
.build());
if (connectionString.getReadPreference() != null) { if (connectionString.getReadPreference() != null) {
builder.readPreference(connectionString.getReadPreference()); builder.readPreference(connectionString.getReadPreference());
} }
......
...@@ -235,8 +235,8 @@ public class EmbeddedMongoAutoConfiguration { ...@@ -235,8 +235,8 @@ public class EmbeddedMongoAutoConfiguration {
@Configuration @Configuration
@ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class, @ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class,
ReactiveMongoClientFactoryBean.class }) ReactiveMongoClientFactoryBean.class })
protected static class EmbeddedReactiveMongoDependencyConfiguration extends protected static class EmbeddedReactiveMongoDependencyConfiguration
ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor { extends ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor {
public EmbeddedReactiveMongoDependencyConfiguration() { public EmbeddedReactiveMongoDependencyConfiguration() {
super("embeddedMongoServer"); super("embeddedMongoServer");
......
...@@ -32,7 +32,7 @@ import org.springframework.context.annotation.Configuration; ...@@ -32,7 +32,7 @@ import org.springframework.context.annotation.Configuration;
* @author Brian Clozel * @author Brian Clozel
*/ */
@Configuration @Configuration
@ConditionalOnClass({Mono.class, Flux.class}) @ConditionalOnClass({ Mono.class, Flux.class })
@EnableConfigurationProperties(ReactorCoreProperties.class) @EnableConfigurationProperties(ReactorCoreProperties.class)
public class ReactorCoreAutoConfiguration { public class ReactorCoreAutoConfiguration {
......
...@@ -47,5 +47,7 @@ public class ReactorCoreProperties { ...@@ -47,5 +47,7 @@ public class ReactorCoreProperties {
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
} }
} }
...@@ -37,6 +37,7 @@ import org.springframework.validation.beanvalidation.SpringValidatorAdapter; ...@@ -37,6 +37,7 @@ import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
* @since 2.0.0
*/ */
public class SpringValidator implements SmartValidator, ApplicationContextAware, public class SpringValidator implements SmartValidator, ApplicationContextAware,
InitializingBean, DisposableBean { InitializingBean, DisposableBean {
......
...@@ -137,7 +137,8 @@ public class DefaultServletContainerCustomizer ...@@ -137,7 +137,8 @@ public class DefaultServletContainerCustomizer
UndertowCustomizer.customizeUndertow(this.serverProperties, this.environment, UndertowCustomizer.customizeUndertow(this.serverProperties, this.environment,
(UndertowEmbeddedServletContainerFactory) container); (UndertowEmbeddedServletContainerFactory) container);
} }
container.addInitializers(new SessionConfiguringInitializer(this.serverProperties.getSession())); container.addInitializers(
new SessionConfiguringInitializer(this.serverProperties.getSession()));
container.addInitializers(new InitParameterConfiguringServletContextInitializer( container.addInitializers(new InitParameterConfiguringServletContextInitializer(
this.serverProperties.getServlet().getContextParameters())); this.serverProperties.getServlet().getContextParameters()));
} }
...@@ -167,8 +168,8 @@ public class DefaultServletContainerCustomizer ...@@ -167,8 +168,8 @@ public class DefaultServletContainerCustomizer
@Override @Override
public void onStartup(ServletContext servletContext) throws ServletException { public void onStartup(ServletContext servletContext) throws ServletException {
if (this.session.getTrackingModes() != null) { if (this.session.getTrackingModes() != null) {
servletContext.setSessionTrackingModes( servletContext
unwrap(this.session.getTrackingModes())); .setSessionTrackingModes(unwrap(this.session.getTrackingModes()));
} }
configureSessionCookie(servletContext.getSessionCookieConfig()); configureSessionCookie(servletContext.getSessionCookieConfig());
} }
...@@ -214,14 +215,15 @@ public class DefaultServletContainerCustomizer ...@@ -214,14 +215,15 @@ public class DefaultServletContainerCustomizer
private static class TomcatCustomizer { private static class TomcatCustomizer {
public static void customizeTomcat(ServerProperties serverProperties, Environment environment, public static void customizeTomcat(ServerProperties serverProperties,
TomcatEmbeddedServletContainerFactory factory) { Environment environment, TomcatEmbeddedServletContainerFactory factory) {
ServerProperties.Tomcat tomcatProperties = serverProperties.getTomcat(); ServerProperties.Tomcat tomcatProperties = serverProperties.getTomcat();
if (tomcatProperties.getBasedir() != null) { if (tomcatProperties.getBasedir() != null) {
factory.setBaseDirectory(tomcatProperties.getBasedir()); factory.setBaseDirectory(tomcatProperties.getBasedir());
} }
factory.setBackgroundProcessorDelay(tomcatProperties.getBackgroundProcessorDelay()); factory.setBackgroundProcessorDelay(
tomcatProperties.getBackgroundProcessorDelay());
customizeRemoteIpValve(serverProperties, environment, factory); customizeRemoteIpValve(serverProperties, environment, factory);
if (tomcatProperties.getMaxThreads() > 0) { if (tomcatProperties.getMaxThreads() > 0) {
customizeMaxThreads(factory, tomcatProperties.getMaxThreads()); customizeMaxThreads(factory, tomcatProperties.getMaxThreads());
...@@ -230,7 +232,8 @@ public class DefaultServletContainerCustomizer ...@@ -230,7 +232,8 @@ public class DefaultServletContainerCustomizer
customizeMinThreads(factory, tomcatProperties.getMinSpareThreads()); customizeMinThreads(factory, tomcatProperties.getMinSpareThreads());
} }
int maxHttpHeaderSize = (serverProperties.getMaxHttpHeaderSize() > 0 int maxHttpHeaderSize = (serverProperties.getMaxHttpHeaderSize() > 0
? serverProperties.getMaxHttpHeaderSize() : tomcatProperties.getMaxHttpHeaderSize()); ? serverProperties.getMaxHttpHeaderSize()
: tomcatProperties.getMaxHttpHeaderSize());
if (maxHttpHeaderSize > 0) { if (maxHttpHeaderSize > 0) {
customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize); customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize);
} }
...@@ -248,7 +251,8 @@ public class DefaultServletContainerCustomizer ...@@ -248,7 +251,8 @@ public class DefaultServletContainerCustomizer
serverProperties.getConnectionTimeout()); serverProperties.getConnectionTimeout());
} }
if (tomcatProperties.getRedirectContextRoot() != null) { if (tomcatProperties.getRedirectContextRoot() != null) {
customizeRedirectContextRoot(factory, tomcatProperties.getRedirectContextRoot()); customizeRedirectContextRoot(factory,
tomcatProperties.getRedirectContextRoot());
} }
if (tomcatProperties.getMaxConnections() > 0) { if (tomcatProperties.getMaxConnections() > 0) {
customizeMaxConnections(factory, tomcatProperties.getMaxConnections()); customizeMaxConnections(factory, tomcatProperties.getMaxConnections());
...@@ -257,12 +261,13 @@ public class DefaultServletContainerCustomizer ...@@ -257,12 +261,13 @@ public class DefaultServletContainerCustomizer
customizeAcceptCount(factory, tomcatProperties.getAcceptCount()); customizeAcceptCount(factory, tomcatProperties.getAcceptCount());
} }
if (!ObjectUtils.isEmpty(tomcatProperties.getAdditionalTldSkipPatterns())) { if (!ObjectUtils.isEmpty(tomcatProperties.getAdditionalTldSkipPatterns())) {
factory.getTldSkipPatterns().addAll(tomcatProperties.getAdditionalTldSkipPatterns()); factory.getTldSkipPatterns()
.addAll(tomcatProperties.getAdditionalTldSkipPatterns());
} }
} }
private static void customizeAcceptCount(TomcatEmbeddedServletContainerFactory factory, private static void customizeAcceptCount(
final int acceptCount) { TomcatEmbeddedServletContainerFactory factory, final int acceptCount) {
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override @Override
...@@ -294,7 +299,8 @@ public class DefaultServletContainerCustomizer ...@@ -294,7 +299,8 @@ public class DefaultServletContainerCustomizer
} }
private static void customizeConnectionTimeout( private static void customizeConnectionTimeout(
TomcatEmbeddedServletContainerFactory factory, final int connectionTimeout) { TomcatEmbeddedServletContainerFactory factory,
final int connectionTimeout) {
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override @Override
...@@ -309,8 +315,8 @@ public class DefaultServletContainerCustomizer ...@@ -309,8 +315,8 @@ public class DefaultServletContainerCustomizer
}); });
} }
private static void customizeRemoteIpValve(ServerProperties properties, Environment environment, private static void customizeRemoteIpValve(ServerProperties properties,
TomcatEmbeddedServletContainerFactory factory) { Environment environment, TomcatEmbeddedServletContainerFactory factory) {
String protocolHeader = properties.getTomcat().getProtocolHeader(); String protocolHeader = properties.getTomcat().getProtocolHeader();
String remoteIpHeader = properties.getTomcat().getRemoteIpHeader(); String remoteIpHeader = properties.getTomcat().getRemoteIpHeader();
// For back compatibility the valve is also enabled if protocol-header is set // For back compatibility the valve is also enabled if protocol-header is set
...@@ -326,15 +332,16 @@ public class DefaultServletContainerCustomizer ...@@ -326,15 +332,16 @@ public class DefaultServletContainerCustomizer
// addresses // addresses
valve.setInternalProxies(properties.getTomcat().getInternalProxies()); valve.setInternalProxies(properties.getTomcat().getInternalProxies());
valve.setPortHeader(properties.getTomcat().getPortHeader()); valve.setPortHeader(properties.getTomcat().getPortHeader());
valve.setProtocolHeaderHttpsValue(properties.getTomcat().getProtocolHeaderHttpsValue()); valve.setProtocolHeaderHttpsValue(
properties.getTomcat().getProtocolHeaderHttpsValue());
// ... so it's safe to add this valve by default. // ... so it's safe to add this valve by default.
factory.addEngineValves(valve); factory.addEngineValves(valve);
} }
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static void customizeMaxThreads(TomcatEmbeddedServletContainerFactory factory, private static void customizeMaxThreads(
final int maxThreads) { TomcatEmbeddedServletContainerFactory factory, final int maxThreads) {
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override @Override
public void customize(Connector connector) { public void customize(Connector connector) {
...@@ -350,7 +357,8 @@ public class DefaultServletContainerCustomizer ...@@ -350,7 +357,8 @@ public class DefaultServletContainerCustomizer
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static void customizeMinThreads(TomcatEmbeddedServletContainerFactory factory, private static void customizeMinThreads(
TomcatEmbeddedServletContainerFactory factory,
final int minSpareThreads) { final int minSpareThreads) {
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override @Override
...@@ -368,7 +376,8 @@ public class DefaultServletContainerCustomizer ...@@ -368,7 +376,8 @@ public class DefaultServletContainerCustomizer
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static void customizeMaxHttpHeaderSize( private static void customizeMaxHttpHeaderSize(
TomcatEmbeddedServletContainerFactory factory, final int maxHttpHeaderSize) { TomcatEmbeddedServletContainerFactory factory,
final int maxHttpHeaderSize) {
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override @Override
...@@ -384,7 +393,8 @@ public class DefaultServletContainerCustomizer ...@@ -384,7 +393,8 @@ public class DefaultServletContainerCustomizer
} }
private static void customizeMaxHttpPostSize( private static void customizeMaxHttpPostSize(
TomcatEmbeddedServletContainerFactory factory, final int maxHttpPostSize) { TomcatEmbeddedServletContainerFactory factory,
final int maxHttpPostSize) {
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override @Override
...@@ -429,10 +439,12 @@ public class DefaultServletContainerCustomizer ...@@ -429,10 +439,12 @@ public class DefaultServletContainerCustomizer
private static class UndertowCustomizer { private static class UndertowCustomizer {
protected static void customizeUndertow(final ServerProperties serverProperties, protected static void customizeUndertow(final ServerProperties serverProperties,
Environment environment, UndertowEmbeddedServletContainerFactory factory) { Environment environment,
UndertowEmbeddedServletContainerFactory factory) {
ServerProperties.Undertow undertowProperties = serverProperties.getUndertow(); ServerProperties.Undertow undertowProperties = serverProperties.getUndertow();
ServerProperties.Undertow.Accesslog accesslogProperties = undertowProperties.getAccesslog(); ServerProperties.Undertow.Accesslog accesslogProperties = undertowProperties
.getAccesslog();
if (undertowProperties.getBufferSize() != null) { if (undertowProperties.getBufferSize() != null) {
factory.setBufferSize(undertowProperties.getBufferSize()); factory.setBufferSize(undertowProperties.getBufferSize());
} }
...@@ -453,13 +465,15 @@ public class DefaultServletContainerCustomizer ...@@ -453,13 +465,15 @@ public class DefaultServletContainerCustomizer
factory.setAccessLogPrefix(accesslogProperties.getPrefix()); factory.setAccessLogPrefix(accesslogProperties.getPrefix());
factory.setAccessLogSuffix(accesslogProperties.getSuffix()); factory.setAccessLogSuffix(accesslogProperties.getSuffix());
factory.setAccessLogRotate(accesslogProperties.isRotate()); factory.setAccessLogRotate(accesslogProperties.isRotate());
factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders(serverProperties, environment)); factory.setUseForwardHeaders(
getOrDeduceUseForwardHeaders(serverProperties, environment));
if (serverProperties.getMaxHttpHeaderSize() > 0) { if (serverProperties.getMaxHttpHeaderSize() > 0) {
customizeMaxHttpHeaderSize(factory, customizeMaxHttpHeaderSize(factory,
serverProperties.getMaxHttpHeaderSize()); serverProperties.getMaxHttpHeaderSize());
} }
if (undertowProperties.getMaxHttpPostSize() > 0) { if (undertowProperties.getMaxHttpPostSize() > 0) {
customizeMaxHttpPostSize(factory, undertowProperties.getMaxHttpPostSize()); customizeMaxHttpPostSize(factory,
undertowProperties.getMaxHttpPostSize());
} }
if (serverProperties.getConnectionTimeout() != null) { if (serverProperties.getConnectionTimeout() != null) {
...@@ -515,7 +529,8 @@ public class DefaultServletContainerCustomizer ...@@ -515,7 +529,8 @@ public class DefaultServletContainerCustomizer
public static void customizeJetty(final ServerProperties serverProperties, public static void customizeJetty(final ServerProperties serverProperties,
Environment environment, JettyEmbeddedServletContainerFactory factory) { Environment environment, JettyEmbeddedServletContainerFactory factory) {
ServerProperties.Jetty jettyProperties = serverProperties.getJetty(); ServerProperties.Jetty jettyProperties = serverProperties.getJetty();
factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders(serverProperties, environment)); factory.setUseForwardHeaders(
getOrDeduceUseForwardHeaders(serverProperties, environment));
if (jettyProperties.getAcceptors() != null) { if (jettyProperties.getAcceptors() != null) {
factory.setAcceptors(jettyProperties.getAcceptors()); factory.setAcceptors(jettyProperties.getAcceptors());
} }
......
...@@ -364,6 +364,7 @@ public class ServerProperties { ...@@ -364,6 +364,7 @@ public class ServerProperties {
* {@link javax.servlet.SessionTrackingMode}. * {@link javax.servlet.SessionTrackingMode}.
*/ */
public enum SessionTrackingMode { public enum SessionTrackingMode {
/** /**
* Send a cookie in response to the client's first request. * Send a cookie in response to the client's first request.
*/ */
...@@ -870,7 +871,6 @@ public class ServerProperties { ...@@ -870,7 +871,6 @@ public class ServerProperties {
return this.accesslog; return this.accesslog;
} }
public static class Accesslog { public static class Accesslog {
/** /**
......
...@@ -405,8 +405,7 @@ public class WebMvcAutoConfiguration { ...@@ -405,8 +405,7 @@ public class WebMvcAutoConfiguration {
getClass().getClassLoader())) { getClass().getClassLoader())) {
return super.mvcValidator(); return super.mvcValidator();
} }
return SpringValidator.get(getApplicationContext(), return SpringValidator.get(getApplicationContext(), getValidator());
getValidator());
} }
@Override @Override
......
...@@ -28,6 +28,7 @@ import org.springframework.core.Ordered; ...@@ -28,6 +28,7 @@ import org.springframework.core.Ordered;
* {@link EmbeddedServletContainerCustomizerBeanPostProcessor} is active. * {@link EmbeddedServletContainerCustomizerBeanPostProcessor} is active.
* *
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0
*/ */
public class DefaultReactiveWebServerCustomizer public class DefaultReactiveWebServerCustomizer
implements ReactiveWebServerCustomizer, Ordered { implements ReactiveWebServerCustomizer, Ordered {
...@@ -57,6 +58,6 @@ public class DefaultReactiveWebServerCustomizer ...@@ -57,6 +58,6 @@ public class DefaultReactiveWebServerCustomizer
if (this.serverProperties.getCompression() != null) { if (this.serverProperties.getCompression() != null) {
server.setCompression(this.serverProperties.getCompression()); server.setCompression(this.serverProperties.getCompression());
} }
} }
} }
...@@ -49,6 +49,7 @@ import org.springframework.web.server.session.WebSessionManager; ...@@ -49,6 +49,7 @@ import org.springframework.web.server.session.WebSessionManager;
* *
* @author Brian Clozel * @author Brian Clozel
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 2.0.0
*/ */
@Configuration @Configuration
@ConditionalOnClass({ DispatcherHandler.class, HttpHandler.class }) @ConditionalOnClass({ DispatcherHandler.class, HttpHandler.class })
...@@ -120,16 +121,17 @@ public class HttpHandlerAutoConfiguration { ...@@ -120,16 +121,17 @@ public class HttpHandlerAutoConfiguration {
if (this.viewResolvers != null) { if (this.viewResolvers != null) {
this.viewResolvers.forEach(strategiesBuilder::viewResolver); this.viewResolvers.forEach(strategiesBuilder::viewResolver);
} }
WebHandler webHandler = RouterFunctions WebHandler webHandler = RouterFunctions.toHttpHandler(routerFunction,
.toHttpHandler(routerFunction, strategiesBuilder.build()); strategiesBuilder.build());
WebHttpHandlerBuilder builder = WebHttpHandlerBuilder WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.webHandler(webHandler)
.webHandler(webHandler)
.sessionManager(this.webSessionManager); .sessionManager(this.webSessionManager);
if (this.webFilters != null) { if (this.webFilters != null) {
builder.filters(this.webFilters.toArray( builder.filters(
new WebFilter[this.webFilters.size()])); this.webFilters.toArray(new WebFilter[this.webFilters.size()]));
} }
return builder.build(); return builder.build();
} }
} }
} }
...@@ -41,16 +41,17 @@ import org.springframework.util.ObjectUtils; ...@@ -41,16 +41,17 @@ import org.springframework.util.ObjectUtils;
* {@link EnableAutoConfiguration Auto-configuration} for a reactive web server. * {@link EnableAutoConfiguration Auto-configuration} for a reactive web server.
* *
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0
*/ */
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration @Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@EnableConfigurationProperties(ServerProperties.class) @EnableConfigurationProperties(ServerProperties.class)
@Import({ReactiveWebServerAutoConfiguration.BeanPostProcessorsRegistrar.class, @Import({ ReactiveWebServerAutoConfiguration.BeanPostProcessorsRegistrar.class,
ReactiveWebServerConfiguration.TomcatAutoConfiguration.class, ReactiveWebServerConfiguration.TomcatAutoConfiguration.class,
ReactiveWebServerConfiguration.JettyAutoConfiguration.class, ReactiveWebServerConfiguration.JettyAutoConfiguration.class,
ReactiveWebServerConfiguration.ReactorNettyAutoConfiguration.class, ReactiveWebServerConfiguration.ReactorNettyAutoConfiguration.class,
ReactiveWebServerConfiguration.UndertowAutoConfiguration.class}) ReactiveWebServerConfiguration.UndertowAutoConfiguration.class })
public class ReactiveWebServerAutoConfiguration { public class ReactiveWebServerAutoConfiguration {
@ConditionalOnMissingBean @ConditionalOnMissingBean
...@@ -61,8 +62,8 @@ public class ReactiveWebServerAutoConfiguration { ...@@ -61,8 +62,8 @@ public class ReactiveWebServerAutoConfiguration {
} }
/** /**
* Registers a {@link ReactiveWebServerCustomizerBeanPostProcessor}. Registered * Registers a {@link ReactiveWebServerCustomizerBeanPostProcessor}. Registered via
* via {@link ImportBeanDefinitionRegistrar} for early registration. * {@link ImportBeanDefinitionRegistrar} for early registration.
*/ */
public static class BeanPostProcessorsRegistrar public static class BeanPostProcessorsRegistrar
implements ImportBeanDefinitionRegistrar, BeanFactoryAware { implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
...@@ -94,4 +95,5 @@ public class ReactiveWebServerAutoConfiguration { ...@@ -94,4 +95,5 @@ public class ReactiveWebServerAutoConfiguration {
} }
} }
} }
...@@ -30,43 +30,51 @@ import org.springframework.context.annotation.Bean; ...@@ -30,43 +30,51 @@ import org.springframework.context.annotation.Bean;
/** /**
* Configuration classes for reactive web servers * Configuration classes for reactive web servers
* <p>Those should be {@code @Import} in a regular auto-configuration class * <p>
* to guarantee their order of execution. * Those should be {@code @Import} in a regular auto-configuration class to guarantee
* their order of execution.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
abstract class ReactiveWebServerConfiguration { abstract class ReactiveWebServerConfiguration {
@ConditionalOnMissingBean(ReactiveWebServerFactory.class) @ConditionalOnMissingBean(ReactiveWebServerFactory.class)
@ConditionalOnClass({HttpServer.class}) @ConditionalOnClass({ HttpServer.class })
static class ReactorNettyAutoConfiguration { static class ReactorNettyAutoConfiguration {
@Bean @Bean
public ReactorNettyReactiveWebServerFactory reactorNettyReactiveWebServerFactory() { public ReactorNettyReactiveWebServerFactory reactorNettyReactiveWebServerFactory() {
return new ReactorNettyReactiveWebServerFactory(); return new ReactorNettyReactiveWebServerFactory();
} }
} }
@ConditionalOnMissingBean(ReactiveWebServerFactory.class) @ConditionalOnMissingBean(ReactiveWebServerFactory.class)
@ConditionalOnClass({org.apache.catalina.startup.Tomcat.class}) @ConditionalOnClass({ org.apache.catalina.startup.Tomcat.class })
static class TomcatAutoConfiguration { static class TomcatAutoConfiguration {
@Bean @Bean
public TomcatReactiveWebServerFactory tomcatReactiveWebServerFactory() { public TomcatReactiveWebServerFactory tomcatReactiveWebServerFactory() {
return new TomcatReactiveWebServerFactory(); return new TomcatReactiveWebServerFactory();
} }
} }
@ConditionalOnMissingBean(ReactiveWebServerFactory.class) @ConditionalOnMissingBean(ReactiveWebServerFactory.class)
@ConditionalOnClass({org.eclipse.jetty.server.Server.class}) @ConditionalOnClass({ org.eclipse.jetty.server.Server.class })
static class JettyAutoConfiguration { static class JettyAutoConfiguration {
@Bean @Bean
public JettyReactiveWebServerFactory jettyReactiveWebServerFactory() { public JettyReactiveWebServerFactory jettyReactiveWebServerFactory() {
return new JettyReactiveWebServerFactory(); return new JettyReactiveWebServerFactory();
} }
} }
@ConditionalOnMissingBean(ReactiveWebServerFactory.class) @ConditionalOnMissingBean(ReactiveWebServerFactory.class)
@ConditionalOnClass({Undertow.class}) @ConditionalOnClass({ Undertow.class })
static class UndertowAutoConfiguration { static class UndertowAutoConfiguration {
@Bean @Bean
public UndertowReactiveWebServerFactory undertowReactiveWebServerFactory() { public UndertowReactiveWebServerFactory undertowReactiveWebServerFactory() {
return new UndertowReactiveWebServerFactory(); return new UndertowReactiveWebServerFactory();
......
...@@ -70,6 +70,7 @@ import org.springframework.web.reactive.result.view.ViewResolver; ...@@ -70,6 +70,7 @@ import org.springframework.web.reactive.result.view.ViewResolver;
* @author Brian Clozel * @author Brian Clozel
* @author Rob Winch * @author Rob Winch
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 2.0.0
*/ */
@Configuration @Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
...@@ -80,7 +81,7 @@ import org.springframework.web.reactive.result.view.ViewResolver; ...@@ -80,7 +81,7 @@ import org.springframework.web.reactive.result.view.ViewResolver;
public class WebFluxAnnotationAutoConfiguration { public class WebFluxAnnotationAutoConfiguration {
@Configuration @Configuration
@EnableConfigurationProperties({ResourceProperties.class, WebFluxProperties.class}) @EnableConfigurationProperties({ ResourceProperties.class, WebFluxProperties.class })
@Import(EnableWebFluxConfiguration.class) @Import(EnableWebFluxConfiguration.class)
public static class WebFluxConfig implements WebFluxConfigurer { public static class WebFluxConfig implements WebFluxConfigurer {
...@@ -98,7 +99,6 @@ public class WebFluxAnnotationAutoConfiguration { ...@@ -98,7 +99,6 @@ public class WebFluxAnnotationAutoConfiguration {
private final List<ViewResolver> viewResolvers; private final List<ViewResolver> viewResolvers;
public WebFluxConfig(ResourceProperties resourceProperties, public WebFluxConfig(ResourceProperties resourceProperties,
WebFluxProperties webFluxProperties, ListableBeanFactory beanFactory, WebFluxProperties webFluxProperties, ListableBeanFactory beanFactory,
ObjectProvider<List<HandlerMethodArgumentResolver>> resolvers, ObjectProvider<List<HandlerMethodArgumentResolver>> resolvers,
...@@ -108,7 +108,8 @@ public class WebFluxAnnotationAutoConfiguration { ...@@ -108,7 +108,8 @@ public class WebFluxAnnotationAutoConfiguration {
this.webFluxProperties = webFluxProperties; this.webFluxProperties = webFluxProperties;
this.beanFactory = beanFactory; this.beanFactory = beanFactory;
this.argumentResolvers = resolvers.getIfAvailable(); this.argumentResolvers = resolvers.getIfAvailable();
this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer.getIfAvailable(); this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer
.getIfAvailable();
this.viewResolvers = viewResolvers.getIfAvailable(); this.viewResolvers = viewResolvers.getIfAvailable();
} }
...@@ -131,16 +132,19 @@ public class WebFluxAnnotationAutoConfiguration { ...@@ -131,16 +132,19 @@ public class WebFluxAnnotationAutoConfiguration {
.addResourceHandler("/webjars/**") .addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/"); .addResourceLocations("classpath:/META-INF/resources/webjars/");
if (cachePeriod != null) { if (cachePeriod != null) {
registration.setCacheControl(CacheControl.maxAge(cachePeriod, TimeUnit.SECONDS)); registration.setCacheControl(
CacheControl.maxAge(cachePeriod, TimeUnit.SECONDS));
} }
customizeResourceHandlerRegistration(registration); customizeResourceHandlerRegistration(registration);
} }
String staticPathPattern = this.webFluxProperties.getStaticPathPattern(); String staticPathPattern = this.webFluxProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) { if (!registry.hasMappingForPattern(staticPathPattern)) {
ResourceHandlerRegistration registration = registry.addResourceHandler(staticPathPattern) ResourceHandlerRegistration registration = registry
.addResourceLocations(this.resourceProperties.getStaticLocations()); .addResourceHandler(staticPathPattern).addResourceLocations(
this.resourceProperties.getStaticLocations());
if (cachePeriod != null) { if (cachePeriod != null) {
registration.setCacheControl(CacheControl.maxAge(cachePeriod, TimeUnit.SECONDS)); registration.setCacheControl(
CacheControl.maxAge(cachePeriod, TimeUnit.SECONDS));
} }
customizeResourceHandlerRegistration(registration); customizeResourceHandlerRegistration(registration);
} }
...@@ -194,8 +198,7 @@ public class WebFluxAnnotationAutoConfiguration { ...@@ -194,8 +198,7 @@ public class WebFluxAnnotationAutoConfiguration {
getClass().getClassLoader())) { getClass().getClassLoader())) {
return super.webFluxValidator(); return super.webFluxValidator();
} }
return SpringValidator.get(getApplicationContext(), return SpringValidator.get(getApplicationContext(), getValidator());
getValidator());
} }
} }
...@@ -208,6 +211,7 @@ public class WebFluxAnnotationAutoConfiguration { ...@@ -208,6 +211,7 @@ public class WebFluxAnnotationAutoConfiguration {
public ResourceChainResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer() { public ResourceChainResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer() {
return new ResourceChainResourceHandlerRegistrationCustomizer(); return new ResourceChainResourceHandlerRegistrationCustomizer();
} }
} }
interface ResourceHandlerRegistrationCustomizer { interface ResourceHandlerRegistrationCustomizer {
...@@ -259,4 +263,5 @@ public class WebFluxAnnotationAutoConfiguration { ...@@ -259,4 +263,5 @@ public class WebFluxAnnotationAutoConfiguration {
} }
} }
} }
...@@ -39,4 +39,5 @@ public class WebFluxProperties { ...@@ -39,4 +39,5 @@ public class WebFluxProperties {
public void setStaticPathPattern(String staticPathPattern) { public void setStaticPathPattern(String staticPathPattern) {
this.staticPathPattern = staticPathPattern; this.staticPathPattern = staticPathPattern;
} }
} }
...@@ -654,7 +654,7 @@ public class CacheAutoConfigurationTests { ...@@ -654,7 +654,7 @@ public class CacheAutoConfigurationTests {
} }
private void load(Class<?> config, String... environment) { private void load(Class<?> config, String... environment) {
load(new Class[]{config}, environment); load(new Class[] { config }, environment);
} }
private void load(Class<?>[] configs, String... environment) { private void load(Class<?>[] configs, String... environment) {
......
...@@ -65,9 +65,9 @@ public class ConditionalOnNotWebApplicationTests { ...@@ -65,9 +65,9 @@ public class ConditionalOnNotWebApplicationTests {
@Test @Test
public void testNotWebApplicationWithReactiveContext() { public void testNotWebApplicationWithReactiveContext() {
GenericReactiveWebApplicationContext ctx = new GenericReactiveWebApplicationContext(); GenericReactiveWebApplicationContext ctx = new GenericReactiveWebApplicationContext();
ctx.register(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class); ctx.register(ReactiveApplicationConfig.class,
NotWebApplicationConfiguration.class);
ctx.refresh(); ctx.refresh();
this.context = ctx; this.context = ctx;
assertThat(this.context.getBeansOfType(String.class)).isEmpty(); assertThat(this.context.getBeansOfType(String.class)).isEmpty();
} }
...@@ -77,10 +77,9 @@ public class ConditionalOnNotWebApplicationTests { ...@@ -77,10 +77,9 @@ public class ConditionalOnNotWebApplicationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(NotWebApplicationConfiguration.class); ctx.register(NotWebApplicationConfiguration.class);
ctx.refresh(); ctx.refresh();
this.context = ctx; this.context = ctx;
assertThat(this.context.getBeansOfType(String.class)).containsExactly( assertThat(this.context.getBeansOfType(String.class))
entry("none", "none")); .containsExactly(entry("none", "none"));
} }
@Configuration @Configuration
...@@ -95,6 +94,7 @@ public class ConditionalOnNotWebApplicationTests { ...@@ -95,6 +94,7 @@ public class ConditionalOnNotWebApplicationTests {
public HttpHandler httpHandler() { public HttpHandler httpHandler() {
return (request, response) -> Mono.empty(); return (request, response) -> Mono.empty();
} }
} }
@Configuration @Configuration
......
...@@ -60,10 +60,9 @@ public class ConditionalOnWebApplicationTests { ...@@ -60,10 +60,9 @@ public class ConditionalOnWebApplicationTests {
ReactiveWebApplicationConfiguration.class); ReactiveWebApplicationConfiguration.class);
ctx.setServletContext(new MockServletContext()); ctx.setServletContext(new MockServletContext());
ctx.refresh(); ctx.refresh();
this.context = ctx; this.context = ctx;
assertThat(this.context.getBeansOfType(String.class)).containsExactly( assertThat(this.context.getBeansOfType(String.class))
entry("any", "any"), entry("servlet", "servlet")); .containsExactly(entry("any", "any"), entry("servlet", "servlet"));
} }
@Test @Test
...@@ -73,10 +72,9 @@ public class ConditionalOnWebApplicationTests { ...@@ -73,10 +72,9 @@ public class ConditionalOnWebApplicationTests {
ServletWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class,
ReactiveWebApplicationConfiguration.class); ReactiveWebApplicationConfiguration.class);
ctx.refresh(); ctx.refresh();
this.context = ctx; this.context = ctx;
assertThat(this.context.getBeansOfType(String.class)).containsExactly( assertThat(this.context.getBeansOfType(String.class))
entry("any", "any"), entry("reactive", "reactive")); .containsExactly(entry("any", "any"), entry("reactive", "reactive"));
} }
@Test @Test
...@@ -86,7 +84,6 @@ public class ConditionalOnWebApplicationTests { ...@@ -86,7 +84,6 @@ public class ConditionalOnWebApplicationTests {
ServletWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class,
ReactiveWebApplicationConfiguration.class); ReactiveWebApplicationConfiguration.class);
ctx.refresh(); ctx.refresh();
this.context = ctx; this.context = ctx;
assertThat(this.context.getBeansOfType(String.class)).isEmpty(); assertThat(this.context.getBeansOfType(String.class)).isEmpty();
} }
...@@ -131,6 +128,7 @@ public class ConditionalOnWebApplicationTests { ...@@ -131,6 +128,7 @@ public class ConditionalOnWebApplicationTests {
public HttpHandler httpHandler() { public HttpHandler httpHandler() {
return (request, response) -> Mono.empty(); return (request, response) -> Mono.empty();
} }
} }
} }
...@@ -60,7 +60,6 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests { ...@@ -60,7 +60,6 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests {
@Test @Test
public void testDefaultRepositoryConfiguration() throws Exception { public void testDefaultRepositoryConfiguration() throws Exception {
prepareApplicationContext(TestConfiguration.class); prepareApplicationContext(TestConfiguration.class);
assertThat(this.context.getBean(ReactiveCityRepository.class)).isNotNull(); assertThat(this.context.getBean(ReactiveCityRepository.class)).isNotNull();
MongoClient client = this.context.getBean(MongoClient.class); MongoClient client = this.context.getBean(MongoClient.class);
assertThat(client).isInstanceOf(MongoClient.class); assertThat(client).isInstanceOf(MongoClient.class);
...@@ -75,7 +74,6 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests { ...@@ -75,7 +74,6 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests {
@Test @Test
public void testNoRepositoryConfiguration() throws Exception { public void testNoRepositoryConfiguration() throws Exception {
prepareApplicationContext(EmptyConfiguration.class); prepareApplicationContext(EmptyConfiguration.class);
MongoClient client = this.context.getBean(MongoClient.class); MongoClient client = this.context.getBean(MongoClient.class);
assertThat(client).isInstanceOf(MongoClient.class); assertThat(client).isInstanceOf(MongoClient.class);
} }
...@@ -83,14 +81,13 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests { ...@@ -83,14 +81,13 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests {
@Test @Test
public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
prepareApplicationContext(CustomizedConfiguration.class); prepareApplicationContext(CustomizedConfiguration.class);
assertThat(this.context.getBeansOfType(ReactiveCityMongoDbRepository.class))
assertThat(this.context.getBeansOfType(ReactiveCityMongoDbRepository.class)).isEmpty(); .isEmpty();
} }
@Test(expected = NoSuchBeanDefinitionException.class) @Test(expected = NoSuchBeanDefinitionException.class)
public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() {
prepareApplicationContext(SortOfInvalidCustomConfiguration.class); prepareApplicationContext(SortOfInvalidCustomConfiguration.class);
this.context.getBean(ReactiveCityRepository.class); this.context.getBean(ReactiveCityRepository.class);
} }
...@@ -98,8 +95,7 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests { ...@@ -98,8 +95,7 @@ public class ReactiveMongoRepositoriesAutoConfigurationTests {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.register(configurationClasses); this.context.register(configurationClasses);
this.context.register(MongoAutoConfiguration.class, this.context.register(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, MongoDataAutoConfiguration.class, ReactiveMongoAutoConfiguration.class,
ReactiveMongoAutoConfiguration.class,
ReactiveMongoDataAutoConfiguration.class, ReactiveMongoDataAutoConfiguration.class,
ReactiveMongoRepositoriesAutoConfiguration.class, ReactiveMongoRepositoriesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class); PropertyPlaceholderAutoConfiguration.class);
......
...@@ -59,7 +59,8 @@ public class ReactiveMongoAutoConfigurationTests { ...@@ -59,7 +59,8 @@ public class ReactiveMongoAutoConfigurationTests {
this.context = new AnnotationConfigApplicationContext( this.context = new AnnotationConfigApplicationContext(
PropertyPlaceholderAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
ReactiveMongoAutoConfiguration.class); ReactiveMongoAutoConfiguration.class);
assertThat(this.context.getBeanNamesForType(MongoClient.class).length).isEqualTo(1); assertThat(this.context.getBeanNamesForType(MongoClient.class).length)
.isEqualTo(1);
} }
@Test @Test
...@@ -84,8 +85,9 @@ public class ReactiveMongoAutoConfigurationTests { ...@@ -84,8 +85,9 @@ public class ReactiveMongoAutoConfigurationTests {
PropertyPlaceholderAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
ReactiveMongoAutoConfiguration.class); ReactiveMongoAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertThat(this.context.getBean(MongoClient.class).getSettings() assertThat(
.getReadPreference()).isEqualTo(ReadPreference.nearest()); this.context.getBean(MongoClient.class).getSettings().getReadPreference())
.isEqualTo(ReadPreference.nearest());
} }
@Test @Test
...@@ -109,12 +111,10 @@ public class ReactiveMongoAutoConfigurationTests { ...@@ -109,12 +111,10 @@ public class ReactiveMongoAutoConfigurationTests {
@Bean @Bean
public MongoClientSettings mongoClientSettings() { public MongoClientSettings mongoClientSettings() {
return MongoClientSettings return MongoClientSettings.builder().readPreference(ReadPreference.nearest())
.builder() .socketSettings(SocketSettings.builder()
.readPreference(ReadPreference.nearest()) .readTimeout(300, TimeUnit.SECONDS).build())
.socketSettings( .build();
SocketSettings.builder().readTimeout(300, TimeUnit.SECONDS)
.build()).build();
} }
} }
...@@ -131,7 +131,8 @@ public class ReactiveMongoAutoConfigurationTests { ...@@ -131,7 +131,8 @@ public class ReactiveMongoAutoConfigurationTests {
@Bean @Bean
public StreamFactoryFactory myStreamFactoryFactory() { public StreamFactoryFactory myStreamFactoryFactory() {
StreamFactoryFactory streamFactoryFactory = mock(StreamFactoryFactory.class); StreamFactoryFactory streamFactoryFactory = mock(StreamFactoryFactory.class);
given(streamFactoryFactory.create(any(), any())).willReturn(mock(StreamFactory.class)); given(streamFactoryFactory.create(any(), any()))
.willReturn(mock(StreamFactory.class));
return streamFactoryFactory; return streamFactoryFactory;
} }
......
...@@ -154,7 +154,8 @@ public class ReactiveMongoClientFactoryTests { ...@@ -154,7 +154,8 @@ public class ReactiveMongoClientFactoryTests {
private MongoClient createMongoClient(MongoProperties properties, private MongoClient createMongoClient(MongoProperties properties,
Environment environment) { Environment environment) {
return new ReactiveMongoClientFactory(properties, environment).createMongoClient(null); return new ReactiveMongoClientFactory(properties, environment)
.createMongoClient(null);
} }
private List<ServerAddress> extractServerAddresses(MongoClient client) { private List<ServerAddress> extractServerAddresses(MongoClient client) {
......
...@@ -31,7 +31,7 @@ import org.springframework.validation.MapBindingResult; ...@@ -31,7 +31,7 @@ import org.springframework.validation.MapBindingResult;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
...@@ -54,8 +54,7 @@ public class SpringValidatorTests { ...@@ -54,8 +54,7 @@ public class SpringValidatorTests {
@Test @Test
public void wrapLocalValidatorFactoryBean() { public void wrapLocalValidatorFactoryBean() {
SpringValidator wrapper = load( SpringValidator wrapper = load(LocalValidatorFactoryBeanConfig.class);
LocalValidatorFactoryBeanConfig.class);
assertThat(wrapper.supports(SampleData.class)).isTrue(); assertThat(wrapper.supports(SampleData.class)).isTrue();
MapBindingResult errors = new MapBindingResult(new HashMap<String, Object>(), MapBindingResult errors = new MapBindingResult(new HashMap<String, Object>(),
"test"); "test");
......
...@@ -702,8 +702,7 @@ public class WebMvcAutoConfigurationTests { ...@@ -702,8 +702,7 @@ public class WebMvcAutoConfigurationTests {
assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1);
Validator validator = this.context.getBean(Validator.class); Validator validator = this.context.getBean(Validator.class);
assertThat(validator).isInstanceOf(SpringValidator.class); assertThat(validator).isInstanceOf(SpringValidator.class);
SpringValidatorAdapter target = ((SpringValidator) validator) SpringValidatorAdapter target = ((SpringValidator) validator).getTarget();
.getTarget();
assertThat(new DirectFieldAccessor(target).getPropertyValue("targetValidator")) assertThat(new DirectFieldAccessor(target).getPropertyValue("targetValidator"))
.isSameAs(this.context.getBean(javax.validation.Validator.class)); .isSameAs(this.context.getBean(javax.validation.Validator.class));
} }
......
...@@ -38,7 +38,6 @@ public class DefaultReactiveWebServerCustomizerTests { ...@@ -38,7 +38,6 @@ public class DefaultReactiveWebServerCustomizerTests {
private DefaultReactiveWebServerCustomizer customizer; private DefaultReactiveWebServerCustomizer customizer;
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
this.customizer = new DefaultReactiveWebServerCustomizer(this.properties); this.customizer = new DefaultReactiveWebServerCustomizer(this.properties);
...@@ -60,4 +59,5 @@ public class DefaultReactiveWebServerCustomizerTests { ...@@ -60,4 +59,5 @@ public class DefaultReactiveWebServerCustomizerTests {
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setAddress(address); verify(factory).setAddress(address);
} }
} }
...@@ -57,8 +57,8 @@ public class HttpHandlerAutoConfigurationTests { ...@@ -57,8 +57,8 @@ public class HttpHandlerAutoConfigurationTests {
public void shouldNotProcessIfExistingHttpHandler() { public void shouldNotProcessIfExistingHttpHandler() {
load(CustomHttpHandler.class); load(CustomHttpHandler.class);
assertThat(this.context.getBeansOfType(HttpHandler.class)).hasSize(1); assertThat(this.context.getBeansOfType(HttpHandler.class)).hasSize(1);
assertThat(this.context.getBean(HttpHandler.class)).isSameAs( assertThat(this.context.getBean(HttpHandler.class))
this.context.getBean("customHttpHandler")); .isSameAs(this.context.getBean("customHttpHandler"));
} }
@Test @Test
...@@ -113,7 +113,6 @@ public class HttpHandlerAutoConfigurationTests { ...@@ -113,7 +113,6 @@ public class HttpHandlerAutoConfigurationTests {
fail("Did not find any FilteringWebHandler"); fail("Did not find any FilteringWebHandler");
} }
private void load(Class<?> config, String... environment) { private void load(Class<?> config, String... environment) {
this.context = new GenericReactiveWebApplicationContext(); this.context = new GenericReactiveWebApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context, environment); EnvironmentTestUtils.addEnvironment(this.context, environment);
...@@ -151,8 +150,10 @@ public class HttpHandlerAutoConfigurationTests { ...@@ -151,8 +150,10 @@ public class HttpHandlerAutoConfigurationTests {
@Bean @Bean
public RouterFunction routerFunction() { public RouterFunction routerFunction() {
return RouterFunctions.route(RequestPredicates.GET("/test"), serverRequest -> null); return RouterFunctions.route(RequestPredicates.GET("/test"),
serverRequest -> null);
} }
} }
@Configuration @Configuration
...@@ -160,13 +161,15 @@ public class HttpHandlerAutoConfigurationTests { ...@@ -160,13 +161,15 @@ public class HttpHandlerAutoConfigurationTests {
@Bean @Bean
public RouterFunction routerFunction() { public RouterFunction routerFunction() {
return RouterFunctions.route(RequestPredicates.GET("/test"), serverRequest -> null); return RouterFunctions.route(RequestPredicates.GET("/test"),
serverRequest -> null);
} }
@Bean @Bean
public WebFilter customWebFilter() { public WebFilter customWebFilter() {
return (serverWebExchange, webFilterChain) -> null; return (serverWebExchange, webFilterChain) -> null;
} }
} }
@Configuration @Configuration
...@@ -179,8 +182,10 @@ public class HttpHandlerAutoConfigurationTests { ...@@ -179,8 +182,10 @@ public class HttpHandlerAutoConfigurationTests {
@Bean @Bean
public RouterFunction routerFunction() { public RouterFunction routerFunction() {
return RouterFunctions.route(RequestPredicates.GET("/test"), serverRequest -> null); return RouterFunctions.route(RequestPredicates.GET("/test"),
serverRequest -> null);
} }
} }
} }
...@@ -93,4 +93,5 @@ public class MockReactiveWebServerFactory extends AbstractReactiveWebServerFacto ...@@ -93,4 +93,5 @@ public class MockReactiveWebServerFactory extends AbstractReactiveWebServerFacto
} }
} }
} }
...@@ -48,47 +48,55 @@ public class ReactiveWebServerAutoConfigurationTests { ...@@ -48,47 +48,55 @@ public class ReactiveWebServerAutoConfigurationTests {
@Test @Test
public void createFromConfigClass() { public void createFromConfigClass() {
this.context = new EmbeddedReactiveWebApplicationContext(BaseConfiguration.class); this.context = new EmbeddedReactiveWebApplicationContext(BaseConfiguration.class);
assertThat(this.context.getBeansOfType(ReactiveWebServerFactory.class))
assertThat(this.context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); .hasSize(1);
assertThat(this.context.getBeansOfType(ReactiveWebServerCustomizer.class)).hasSize(1); assertThat(this.context.getBeansOfType(ReactiveWebServerCustomizer.class))
assertThat(this.context.getBeansOfType(DefaultReactiveWebServerCustomizer.class)).hasSize(1); .hasSize(1);
assertThat(this.context.getBeansOfType(DefaultReactiveWebServerCustomizer.class))
.hasSize(1);
} }
@Test @Test
public void missingHttpHandler() { public void missingHttpHandler() {
this.thrown.expect(ApplicationContextException.class); this.thrown.expect(ApplicationContextException.class);
this.thrown.expectMessage(Matchers.containsString("missing HttpHandler bean")); this.thrown.expectMessage(Matchers.containsString("missing HttpHandler bean"));
this.context = new EmbeddedReactiveWebApplicationContext(MissingHttpHandlerConfiguration.class); this.context = new EmbeddedReactiveWebApplicationContext(
MissingHttpHandlerConfiguration.class);
} }
@Test @Test
public void multipleHttpHandler() { public void multipleHttpHandler() {
this.thrown.expect(ApplicationContextException.class); this.thrown.expect(ApplicationContextException.class);
this.thrown.expectMessage(Matchers this.thrown.expectMessage(Matchers.containsString(
.containsString("multiple HttpHandler beans : httpHandler,additionalHttpHandler")); "multiple HttpHandler beans : httpHandler,additionalHttpHandler"));
this.context = new EmbeddedReactiveWebApplicationContext(BaseConfiguration.class, TooManyHttpHandlers.class); this.context = new EmbeddedReactiveWebApplicationContext(BaseConfiguration.class,
TooManyHttpHandlers.class);
} }
@Test @Test
public void customizeReactiveWebServer() { public void customizeReactiveWebServer() {
this.context = new EmbeddedReactiveWebApplicationContext(BaseConfiguration.class, this.context = new EmbeddedReactiveWebApplicationContext(BaseConfiguration.class,
ReactiveWebServerCustomization.class); ReactiveWebServerCustomization.class);
MockReactiveWebServerFactory factory = this.context.getBean(MockReactiveWebServerFactory.class); MockReactiveWebServerFactory factory = this.context
.getBean(MockReactiveWebServerFactory.class);
assertThat(factory.getPort()).isEqualTo(9000); assertThat(factory.getPort()).isEqualTo(9000);
} }
@Configuration @Configuration
@Import({MockWebServerAutoConfiguration.class, ReactiveWebServerAutoConfiguration.class}) @Import({ MockWebServerAutoConfiguration.class,
ReactiveWebServerAutoConfiguration.class })
protected static class BaseConfiguration { protected static class BaseConfiguration {
@Bean @Bean
public HttpHandler httpHandler() { public HttpHandler httpHandler() {
return Mockito.mock(HttpHandler.class); return Mockito.mock(HttpHandler.class);
} }
} }
@Configuration @Configuration
@Import({MockWebServerAutoConfiguration.class, ReactiveWebServerAutoConfiguration.class}) @Import({ MockWebServerAutoConfiguration.class,
ReactiveWebServerAutoConfiguration.class })
protected static class MissingHttpHandlerConfiguration { protected static class MissingHttpHandlerConfiguration {
} }
...@@ -100,6 +108,7 @@ public class ReactiveWebServerAutoConfigurationTests { ...@@ -100,6 +108,7 @@ public class ReactiveWebServerAutoConfigurationTests {
public HttpHandler additionalHttpHandler() { public HttpHandler additionalHttpHandler() {
return Mockito.mock(HttpHandler.class); return Mockito.mock(HttpHandler.class);
} }
} }
@Configuration @Configuration
...@@ -109,6 +118,7 @@ public class ReactiveWebServerAutoConfigurationTests { ...@@ -109,6 +118,7 @@ public class ReactiveWebServerAutoConfigurationTests {
public ReactiveWebServerCustomizer reactiveWebServerCustomizer() { public ReactiveWebServerCustomizer reactiveWebServerCustomizer() {
return (server) -> server.setPort(9000); return (server) -> server.setPort(9000);
} }
} }
@Configuration @Configuration
...@@ -118,5 +128,7 @@ public class ReactiveWebServerAutoConfigurationTests { ...@@ -118,5 +128,7 @@ public class ReactiveWebServerAutoConfigurationTests {
public MockReactiveWebServerFactory mockReactiveWebServerFactory() { public MockReactiveWebServerFactory mockReactiveWebServerFactory() {
return new MockReactiveWebServerFactory(); return new MockReactiveWebServerFactory();
} }
} }
} }
...@@ -67,23 +67,21 @@ public class WebFluxAnnotationAutoConfigurationTests { ...@@ -67,23 +67,21 @@ public class WebFluxAnnotationAutoConfigurationTests {
@Test @Test
public void shouldNotProcessIfExistingWebReactiveConfiguration() throws Exception { public void shouldNotProcessIfExistingWebReactiveConfiguration() throws Exception {
load(WebFluxConfigurationSupport.class); load(WebFluxConfigurationSupport.class);
assertThat(this.context.getBeansOfType(RequestMappingHandlerMapping.class).size())
assertThat(this.context.getBeansOfType(RequestMappingHandlerMapping.class) .isEqualTo(1);
.size()).isEqualTo(1); assertThat(this.context.getBeansOfType(RequestMappingHandlerAdapter.class).size())
assertThat(this.context.getBeansOfType(RequestMappingHandlerAdapter.class) .isEqualTo(1);
.size()).isEqualTo(1);
} }
@Test @Test
public void shouldCreateDefaultBeans() throws Exception { public void shouldCreateDefaultBeans() throws Exception {
load(); load();
assertThat(this.context.getBeansOfType(RequestMappingHandlerMapping.class).size())
assertThat(this.context.getBeansOfType(RequestMappingHandlerMapping.class) .isEqualTo(1);
.size()).isEqualTo(1); assertThat(this.context.getBeansOfType(RequestMappingHandlerAdapter.class).size())
assertThat(this.context.getBeansOfType(RequestMappingHandlerAdapter.class) .isEqualTo(1);
.size()).isEqualTo(1); assertThat(this.context.getBeansOfType(CompositeContentTypeResolver.class).size())
assertThat(this.context.getBeansOfType(CompositeContentTypeResolver.class) .isEqualTo(1);
.size()).isEqualTo(1);
assertThat(this.context.getBean("resourceHandlerMapping", HandlerMapping.class)) assertThat(this.context.getBean("resourceHandlerMapping", HandlerMapping.class))
.isNotNull(); .isNotNull();
} }
...@@ -91,18 +89,18 @@ public class WebFluxAnnotationAutoConfigurationTests { ...@@ -91,18 +89,18 @@ public class WebFluxAnnotationAutoConfigurationTests {
@Test @Test
public void shouldRegisterCustomHandlerMethodArgumentResolver() throws Exception { public void shouldRegisterCustomHandlerMethodArgumentResolver() throws Exception {
load(CustomArgumentResolvers.class); load(CustomArgumentResolvers.class);
RequestMappingHandlerAdapter adapter = this.context
RequestMappingHandlerAdapter adapter = this.context.getBean( .getBean(RequestMappingHandlerAdapter.class);
RequestMappingHandlerAdapter.class);
assertThat(adapter.getArgumentResolvers()).contains( assertThat(adapter.getArgumentResolvers()).contains(
this.context.getBean("firstResolver", HandlerMethodArgumentResolver.class), this.context.getBean("firstResolver",
this.context.getBean("secondResolver", HandlerMethodArgumentResolver.class)); HandlerMethodArgumentResolver.class),
this.context.getBean("secondResolver",
HandlerMethodArgumentResolver.class));
} }
@Test @Test
public void shouldRegisterResourceHandlerMapping() throws Exception { public void shouldRegisterResourceHandlerMapping() throws Exception {
load(); load();
SimpleUrlHandlerMapping hm = this.context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping hm = this.context.getBean("resourceHandlerMapping",
SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping.class);
assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class);
...@@ -153,12 +151,11 @@ public class WebFluxAnnotationAutoConfigurationTests { ...@@ -153,12 +151,11 @@ public class WebFluxAnnotationAutoConfigurationTests {
@Test @Test
public void shouldRegisterViewResolvers() throws Exception { public void shouldRegisterViewResolvers() throws Exception {
load(ViewResolvers.class); load(ViewResolvers.class);
ViewResolutionResultHandler resultHandler = this.context.getBean( ViewResolutionResultHandler resultHandler = this.context
ViewResolutionResultHandler.class); .getBean(ViewResolutionResultHandler.class);
assertThat(resultHandler.getViewResolvers()).containsExactly( assertThat(resultHandler.getViewResolvers()).containsExactly(
this.context.getBean("aViewResolver", ViewResolver.class), this.context.getBean("aViewResolver", ViewResolver.class),
this.context.getBean("anotherViewResolver", ViewResolver.class) this.context.getBean("anotherViewResolver", ViewResolver.class));
);
} }
@Test @Test
...@@ -217,8 +214,7 @@ public class WebFluxAnnotationAutoConfigurationTests { ...@@ -217,8 +214,7 @@ public class WebFluxAnnotationAutoConfigurationTests {
assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1);
Validator validator = this.context.getBean(Validator.class); Validator validator = this.context.getBean(Validator.class);
assertThat(validator).isInstanceOf(SpringValidator.class); assertThat(validator).isInstanceOf(SpringValidator.class);
SpringValidatorAdapter target = ((SpringValidator) validator) SpringValidatorAdapter target = ((SpringValidator) validator).getTarget();
.getTarget();
assertThat(new DirectFieldAccessor(target).getPropertyValue("targetValidator")) assertThat(new DirectFieldAccessor(target).getPropertyValue("targetValidator"))
.isSameAs(this.context.getBean(javax.validation.Validator.class)); .isSameAs(this.context.getBean(javax.validation.Validator.class));
} }
...@@ -268,7 +264,7 @@ public class WebFluxAnnotationAutoConfigurationTests { ...@@ -268,7 +264,7 @@ public class WebFluxAnnotationAutoConfigurationTests {
} }
@Configuration @Configuration
@Import({WebFluxAnnotationAutoConfiguration.class}) @Import({ WebFluxAnnotationAutoConfiguration.class })
@EnableConfigurationProperties(WebFluxProperties.class) @EnableConfigurationProperties(WebFluxProperties.class)
protected static class BaseConfiguration { protected static class BaseConfiguration {
......
...@@ -161,7 +161,7 @@ public class DevToolsIntegrationTests { ...@@ -161,7 +161,7 @@ public class DevToolsIntegrationTests {
private static final class ControllerBuilder { private static final class ControllerBuilder {
private final List<String> mappings = new ArrayList<String>(); private final List<String> mappings = new ArrayList<>();
private final String name; private final String name;
......
...@@ -38,7 +38,7 @@ public class ExplodedRemoteApplicationLauncher extends RemoteApplicationLauncher ...@@ -38,7 +38,7 @@ public class ExplodedRemoteApplicationLauncher extends RemoteApplicationLauncher
appDirectory.mkdirs(); appDirectory.mkdirs();
FileSystemUtils.copyRecursively(new File("target/test-classes/com"), FileSystemUtils.copyRecursively(new File("target/test-classes/com"),
new File("target/app/com")); new File("target/app/com"));
List<String> entries = new ArrayList<String>(); List<String> entries = new ArrayList<>();
entries.add("target/app"); entries.add("target/app");
for (File jar : new File("target/dependencies").listFiles()) { for (File jar : new File("target/dependencies").listFiles()) {
entries.add(jar.getAbsolutePath()); entries.add(jar.getAbsolutePath());
......
...@@ -52,7 +52,7 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher ...@@ -52,7 +52,7 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher
new File("target/app/com")); new File("target/app/com"));
addToJar(output, new File("target/app/"), new File("target/app/")); addToJar(output, new File("target/app/"), new File("target/app/"));
output.close(); output.close();
List<String> entries = new ArrayList<String>(); List<String> entries = new ArrayList<>();
entries.add("target/app/app.jar"); entries.add("target/app/app.jar");
for (File jar : new File("target/dependencies").listFiles()) { for (File jar : new File("target/dependencies").listFiles()) {
entries.add(jar.getAbsolutePath()); entries.add(jar.getAbsolutePath());
......
...@@ -45,7 +45,7 @@ class JvmLauncher implements TestRule { ...@@ -45,7 +45,7 @@ class JvmLauncher implements TestRule {
} }
LaunchedJvm launch(String name, String classpath, String... args) throws IOException { LaunchedJvm launch(String name, String classpath, String... args) throws IOException {
List<String> command = new ArrayList<String>(Arrays List<String> command = new ArrayList<>(Arrays
.asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath)); .asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath));
command.addAll(Arrays.asList(args)); command.addAll(Arrays.asList(args));
File standardOut = new File(this.outputDirectory, name + ".out"); File standardOut = new File(this.outputDirectory, name + ".out");
......
...@@ -46,7 +46,7 @@ public class LocalApplicationLauncher implements ApplicationLauncher { ...@@ -46,7 +46,7 @@ public class LocalApplicationLauncher implements ApplicationLauncher {
appDirectory.mkdirs(); appDirectory.mkdirs();
FileSystemUtils.copyRecursively(new File("target/test-classes/com"), FileSystemUtils.copyRecursively(new File("target/test-classes/com"),
new File("target/app/com")); new File("target/app/com"));
List<String> entries = new ArrayList<String>(); List<String> entries = new ArrayList<>();
entries.add("target/app"); entries.add("target/app");
for (File jar : new File("target/dependencies").listFiles()) { for (File jar : new File("target/dependencies").listFiles()) {
entries.add(jar.getAbsolutePath()); entries.add(jar.getAbsolutePath());
......
...@@ -58,7 +58,7 @@ abstract class RemoteApplicationLauncher implements ApplicationLauncher { ...@@ -58,7 +58,7 @@ abstract class RemoteApplicationLauncher implements ApplicationLauncher {
remoteDirectory.mkdirs(); remoteDirectory.mkdirs();
FileSystemUtils.copyRecursively(new File("target/test-classes/com"), FileSystemUtils.copyRecursively(new File("target/test-classes/com"),
new File("target/remote/com")); new File("target/remote/com"));
List<String> entries = new ArrayList<String>(); List<String> entries = new ArrayList<>();
entries.add("target/remote"); entries.add("target/remote");
for (File jar : new File("target/dependencies").listFiles()) { for (File jar : new File("target/dependencies").listFiles()) {
entries.add(jar.getAbsolutePath()); entries.add(jar.getAbsolutePath());
......
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
package sample.webflux; package sample.webflux;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
......
...@@ -40,10 +40,7 @@ public class SampleWebFluxApplicationIntegrationTests { ...@@ -40,10 +40,7 @@ public class SampleWebFluxApplicationIntegrationTests {
@Test @Test
public void testWelcome() throws Exception { public void testWelcome() throws Exception {
this.webClient this.webClient.get().uri("/").accept(MediaType.TEXT_PLAIN).exchange()
.get().uri("/")
.accept(MediaType.TEXT_PLAIN)
.exchange()
.expectBody(String.class).value().isEqualTo("Hello World"); .expectBody(String.class).value().isEqualTo("Hello World");
} }
......
...@@ -37,5 +37,4 @@ public class SampleWebFluxApplicationTests { ...@@ -37,5 +37,4 @@ public class SampleWebFluxApplicationTests {
} }
} }
...@@ -59,7 +59,7 @@ public class SpringBootDependencyInjectionTestExecutionListener ...@@ -59,7 +59,7 @@ public class SpringBootDependencyInjectionTestExecutionListener
@Override @Override
public Set<Class<? extends TestExecutionListener>> postProcessDefaultTestExecutionListeners( public Set<Class<? extends TestExecutionListener>> postProcessDefaultTestExecutionListeners(
Set<Class<? extends TestExecutionListener>> listeners) { Set<Class<? extends TestExecutionListener>> listeners) {
Set<Class<? extends TestExecutionListener>> updated = new LinkedHashSet<Class<? extends TestExecutionListener>>( Set<Class<? extends TestExecutionListener>> updated = new LinkedHashSet<>(
listeners.size()); listeners.size());
for (Class<? extends TestExecutionListener> listener : listeners) { for (Class<? extends TestExecutionListener> listener : listeners) {
updated.add( updated.add(
......
...@@ -55,7 +55,7 @@ public class FilterAnnotations implements Iterable<TypeFilter> { ...@@ -55,7 +55,7 @@ public class FilterAnnotations implements Iterable<TypeFilter> {
} }
private List<TypeFilter> createTypeFilters(Filter[] filters) { private List<TypeFilter> createTypeFilters(Filter[] filters) {
List<TypeFilter> typeFilters = new ArrayList<TypeFilter>(); List<TypeFilter> typeFilters = new ArrayList<>();
for (Filter filter : filters) { for (Filter filter : filters) {
for (Class<?> filterClass : filter.classes()) { for (Class<?> filterClass : filter.classes()) {
typeFilters.add(createTypeFilter(filter.type(), filterClass)); typeFilters.add(createTypeFilter(filter.type(), filterClass));
......
...@@ -50,7 +50,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { ...@@ -50,7 +50,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
private Set<TypeExcludeFilter> instantiateTypeExcludeFilters(Class<?> testClass, private Set<TypeExcludeFilter> instantiateTypeExcludeFilters(Class<?> testClass,
Set<Class<? extends TypeExcludeFilter>> filterClasses) { Set<Class<? extends TypeExcludeFilter>> filterClasses) {
Set<TypeExcludeFilter> filters = new LinkedHashSet<TypeExcludeFilter>(); Set<TypeExcludeFilter> filters = new LinkedHashSet<>();
for (Class<? extends TypeExcludeFilter> filterClass : filterClasses) { for (Class<? extends TypeExcludeFilter> filterClass : filterClasses) {
filters.add(instantiateTypeExcludeFilter(testClass, filterClass)); filters.add(instantiateTypeExcludeFilter(testClass, filterClass));
} }
......
...@@ -42,7 +42,7 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac ...@@ -42,7 +42,7 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac
TypeExcludeFilters annotation = AnnotatedElementUtils TypeExcludeFilters annotation = AnnotatedElementUtils
.findMergedAnnotation(testClass, TypeExcludeFilters.class); .findMergedAnnotation(testClass, TypeExcludeFilters.class);
if (annotation != null) { if (annotation != null) {
Set<Class<? extends TypeExcludeFilter>> filterClasses = new LinkedHashSet<Class<? extends TypeExcludeFilter>>( Set<Class<? extends TypeExcludeFilter>> filterClasses = new LinkedHashSet<>(
Arrays.asList(annotation.value())); Arrays.asList(annotation.value()));
return new TypeExcludeFiltersContextCustomizer(testClass, filterClasses); return new TypeExcludeFiltersContextCustomizer(testClass, filterClasses);
} }
......
...@@ -38,7 +38,7 @@ class JsonExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -38,7 +38,7 @@ class JsonExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private static final Set<Class<?>> DEFAULT_INCLUDES; private static final Set<Class<?>> DEFAULT_INCLUDES;
static { static {
Set<Class<?>> includes = new LinkedHashSet<Class<?>>(); Set<Class<?>> includes = new LinkedHashSet<>();
includes.add(Module.class); includes.add(Module.class);
includes.add(JsonComponent.class); includes.add(JsonComponent.class);
DEFAULT_INCLUDES = Collections.unmodifiableSet(includes); DEFAULT_INCLUDES = Collections.unmodifiableSet(includes);
......
...@@ -74,7 +74,7 @@ public class JsonTestersAutoConfiguration { ...@@ -74,7 +74,7 @@ public class JsonTestersAutoConfiguration {
@ConditionalOnBean(ObjectMapper.class) @ConditionalOnBean(ObjectMapper.class)
public FactoryBean<JacksonTester<?>> jacksonTesterFactoryBean( public FactoryBean<JacksonTester<?>> jacksonTesterFactoryBean(
ObjectMapper mapper) { ObjectMapper mapper) {
return new JsonTesterFactoryBean<JacksonTester<?>, ObjectMapper>( return new JsonTesterFactoryBean<>(
JacksonTester.class, mapper); JacksonTester.class, mapper);
} }
...@@ -87,7 +87,7 @@ public class JsonTestersAutoConfiguration { ...@@ -87,7 +87,7 @@ public class JsonTestersAutoConfiguration {
@Scope("prototype") @Scope("prototype")
@ConditionalOnBean(Gson.class) @ConditionalOnBean(Gson.class)
public FactoryBean<GsonTester<?>> gsonTesterFactoryBean(Gson gson) { public FactoryBean<GsonTester<?>> gsonTesterFactoryBean(Gson gson) {
return new JsonTesterFactoryBean<GsonTester<?>, Gson>(GsonTester.class, gson); return new JsonTesterFactoryBean<>(GsonTester.class, gson);
} }
} }
......
...@@ -59,7 +59,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> ...@@ -59,7 +59,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
} }
private Map<String, Object> getProperties(Class<?> source) { private Map<String, Object> getProperties(Class<?> source) {
Map<String, Object> properties = new LinkedHashMap<String, Object>(); Map<String, Object> properties = new LinkedHashMap<>();
collectProperties(source, source, properties, new HashSet<Class<?>>()); collectProperties(source, source, properties, new HashSet<Class<?>>());
return Collections.unmodifiableMap(properties); return Collections.unmodifiableMap(properties);
} }
...@@ -84,7 +84,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> ...@@ -84,7 +84,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
} }
private List<Annotation> getMergedAnnotations(Class<?> root, Class<?> source) { private List<Annotation> getMergedAnnotations(Class<?> root, Class<?> source) {
List<Annotation> mergedAnnotations = new ArrayList<Annotation>(); List<Annotation> mergedAnnotations = new ArrayList<>();
for (Annotation annotation : AnnotationUtils.getAnnotations(source)) { for (Annotation annotation : AnnotationUtils.getAnnotations(source)) {
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) {
mergedAnnotations mergedAnnotations
......
...@@ -76,8 +76,8 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { ...@@ -76,8 +76,8 @@ class PropertyMappingContextCustomizer implements ContextCustomizer {
public Object postProcessBeforeInitialization(Object bean, String beanName) public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException { throws BeansException {
Class<?> beanClass = bean.getClass(); Class<?> beanClass = bean.getClass();
Set<Class<?>> components = new LinkedHashSet<Class<?>>(); Set<Class<?>> components = new LinkedHashSet<>();
Set<Class<?>> propertyMappings = new LinkedHashSet<Class<?>>(); Set<Class<?>> propertyMappings = new LinkedHashSet<>();
while (beanClass != null) { while (beanClass != null) {
for (Annotation annotation : AnnotationUtils.getAnnotations(beanClass)) { for (Annotation annotation : AnnotationUtils.getAnnotations(beanClass)) {
if (isAnnotated(annotation, Component.class)) { if (isAnnotated(annotation, Component.class)) {
......
...@@ -40,7 +40,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -40,7 +40,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private static final Set<Class<?>> DEFAULT_INCLUDES; private static final Set<Class<?>> DEFAULT_INCLUDES;
static { static {
Set<Class<?>> includes = new LinkedHashSet<Class<?>>(); Set<Class<?>> includes = new LinkedHashSet<>();
if (ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", if (ClassUtils.isPresent("com.fasterxml.jackson.databind.Module",
RestClientExcludeFilter.class.getClassLoader())) { RestClientExcludeFilter.class.getClassLoader())) {
try { try {
...@@ -91,7 +91,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -91,7 +91,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
@Override @Override
protected Set<Class<?>> getComponentIncludes() { protected Set<Class<?>> getComponentIncludes() {
return new LinkedHashSet<Class<?>>(Arrays.asList(this.annotation.components())); return new LinkedHashSet<>(Arrays.asList(this.annotation.components()));
} }
} }
...@@ -50,9 +50,9 @@ import org.springframework.test.web.reactive.server.WebTestClient; ...@@ -50,9 +50,9 @@ import org.springframework.test.web.reactive.server.WebTestClient;
* {@link WebTestClient}. For more fine-grained control of WebTestClient the * {@link WebTestClient}. For more fine-grained control of WebTestClient the
* {@link AutoConfigureWebTestClient @AutoConfigureWebTestClient} annotation can be used. * {@link AutoConfigureWebTestClient @AutoConfigureWebTestClient} annotation can be used.
* <p> * <p>
* Typically {@code @WebFluxTest} is used in combination with {@link MockBean @MockBean} or * Typically {@code @WebFluxTest} is used in combination with {@link MockBean @MockBean}
* {@link Import @Import} to create any collaborators required by your {@code @Controller} * or {@link Import @Import} to create any collaborators required by your
* beans. * {@code @Controller} beans.
* <p> * <p>
* If you are looking to load your full application configuration and use WebTestClient, * If you are looking to load your full application configuration and use WebTestClient,
* you should consider {@link SpringBootTest @SpringBootTest} combined with * you should consider {@link SpringBootTest @SpringBootTest} combined with
......
...@@ -41,7 +41,7 @@ class WebFluxTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -41,7 +41,7 @@ class WebFluxTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private static final Set<Class<?>> DEFAULT_INCLUDES; private static final Set<Class<?>> DEFAULT_INCLUDES;
static { static {
Set<Class<?>> includes = new LinkedHashSet<Class<?>>(); Set<Class<?>> includes = new LinkedHashSet<>();
includes.add(ControllerAdvice.class); includes.add(ControllerAdvice.class);
includes.add(JsonComponent.class); includes.add(JsonComponent.class);
includes.add(WebFluxConfigurer.class); includes.add(WebFluxConfigurer.class);
...@@ -51,7 +51,7 @@ class WebFluxTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -51,7 +51,7 @@ class WebFluxTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private static final Set<Class<?>> DEFAULT_INCLUDES_AND_CONTROLLER; private static final Set<Class<?>> DEFAULT_INCLUDES_AND_CONTROLLER;
static { static {
Set<Class<?>> includes = new LinkedHashSet<Class<?>>(DEFAULT_INCLUDES); Set<Class<?>> includes = new LinkedHashSet<>(DEFAULT_INCLUDES);
includes.add(Controller.class); includes.add(Controller.class);
DEFAULT_INCLUDES_AND_CONTROLLER = Collections.unmodifiableSet(includes); DEFAULT_INCLUDES_AND_CONTROLLER = Collections.unmodifiableSet(includes);
} }
......
...@@ -28,6 +28,7 @@ import org.springframework.web.reactive.function.client.WebClient; ...@@ -28,6 +28,7 @@ import org.springframework.web.reactive.function.client.WebClient;
* Auto-configuration for {@link WebTestClient}. * Auto-configuration for {@link WebTestClient}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 2.0.0
*/ */
@Configuration @Configuration
@ConditionalOnClass({ WebClient.class, WebTestClient.class }) @ConditionalOnClass({ WebClient.class, WebTestClient.class })
......
...@@ -192,7 +192,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi ...@@ -192,7 +192,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi
private static class Printer implements ResultValuePrinter { private static class Printer implements ResultValuePrinter {
private final List<String> lines = new ArrayList<String>(); private final List<String> lines = new ArrayList<>();
@Override @Override
public void printHeading(String heading) { public void printHeading(String heading) {
...@@ -238,7 +238,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi ...@@ -238,7 +238,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi
private final LinesWriter delegate; private final LinesWriter delegate;
private final List<String> lines = new ArrayList<String>(); private final List<String> lines = new ArrayList<>();
DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) { DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) {
Assert.state(context instanceof ConfigurableApplicationContext, Assert.state(context instanceof ConfigurableApplicationContext,
......
...@@ -50,7 +50,7 @@ class WebDriverScope implements Scope { ...@@ -50,7 +50,7 @@ class WebDriverScope implements Scope {
private static final String[] BEAN_CLASSES = { WEB_DRIVER_CLASS, private static final String[] BEAN_CLASSES = { WEB_DRIVER_CLASS,
"org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder" }; "org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder" };
private final Map<String, Object> instances = new HashMap<String, Object>(); private final Map<String, Object> instances = new HashMap<>();
@Override @Override
public Object get(String name, ObjectFactory<?> objectFactory) { public Object get(String name, ObjectFactory<?> objectFactory) {
......
...@@ -45,7 +45,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -45,7 +45,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private static final Set<Class<?>> DEFAULT_INCLUDES; private static final Set<Class<?>> DEFAULT_INCLUDES;
static { static {
Set<Class<?>> includes = new LinkedHashSet<Class<?>>(); Set<Class<?>> includes = new LinkedHashSet<>();
includes.add(ControllerAdvice.class); includes.add(ControllerAdvice.class);
includes.add(JsonComponent.class); includes.add(JsonComponent.class);
includes.add(WebMvcConfigurer.class); includes.add(WebMvcConfigurer.class);
...@@ -60,7 +60,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -60,7 +60,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private static final Set<Class<?>> DEFAULT_INCLUDES_AND_CONTROLLER; private static final Set<Class<?>> DEFAULT_INCLUDES_AND_CONTROLLER;
static { static {
Set<Class<?>> includes = new LinkedHashSet<Class<?>>(DEFAULT_INCLUDES); Set<Class<?>> includes = new LinkedHashSet<>(DEFAULT_INCLUDES);
includes.add(Controller.class); includes.add(Controller.class);
DEFAULT_INCLUDES_AND_CONTROLLER = Collections.unmodifiableSet(includes); DEFAULT_INCLUDES_AND_CONTROLLER = Collections.unmodifiableSet(includes);
} }
...@@ -103,7 +103,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { ...@@ -103,7 +103,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
@Override @Override
protected Set<Class<?>> getComponentIncludes() { protected Set<Class<?>> getComponentIncludes() {
return new LinkedHashSet<Class<?>>(Arrays.asList(this.annotation.controllers())); return new LinkedHashSet<>(Arrays.asList(this.annotation.controllers()));
} }
} }
...@@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; ...@@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest @SpringBootTest
public class SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests { public class SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests {
private List<String> calls = new ArrayList<String>(); private List<String> calls = new ArrayList<>();
@PostConstruct @PostConstruct
public void postConstruct() { public void postConstruct() {
......
...@@ -76,7 +76,8 @@ public class TestDatabaseAutoConfigurationTests { ...@@ -76,7 +76,8 @@ public class TestDatabaseAutoConfigurationTests {
this.context = doLoad(config, environment); this.context = doLoad(config, environment);
} }
private ConfigurableApplicationContext doLoad(Class<?> config, String... environment) { private ConfigurableApplicationContext doLoad(Class<?> config,
String... environment) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
if (config != null) { if (config != null) {
ctx.register(config); ctx.register(config);
......
...@@ -31,8 +31,8 @@ public class RestDocsTestController { ...@@ -31,8 +31,8 @@ public class RestDocsTestController {
@ResponseBody @ResponseBody
@RequestMapping(path = "/", produces = MediaTypes.HAL_JSON_VALUE) @RequestMapping(path = "/", produces = MediaTypes.HAL_JSON_VALUE)
public Map<String, Object> index() { public Map<String, Object> index() {
Map<String, Object> response = new HashMap<String, Object>(); Map<String, Object> response = new HashMap<>();
Map<String, String> links = new HashMap<String, String>(); Map<String, String> links = new HashMap<>();
links.put("self", ControllerLinkBuilder.linkTo(getClass()).toUri().toString()); links.put("self", ControllerLinkBuilder.linkTo(getClass()).toUri().toString());
response.put("_links", links); response.put("_links", links);
return response; return response;
......
...@@ -25,4 +25,5 @@ import org.springframework.stereotype.Service; ...@@ -25,4 +25,5 @@ import org.springframework.stereotype.Service;
*/ */
@Service @Service
public class ExampleRealService { public class ExampleRealService {
} }
...@@ -25,4 +25,5 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; ...@@ -25,4 +25,5 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
*/ */
@SpringBootApplication @SpringBootApplication
public class ExampleWebFluxApplication { public class ExampleWebFluxApplication {
} }
...@@ -37,19 +37,13 @@ public class WebFluxTestAllControllersIntegrationTests { ...@@ -37,19 +37,13 @@ public class WebFluxTestAllControllersIntegrationTests {
@Test @Test
public void shouldFindController1() { public void shouldFindController1() {
this.webClient this.webClient.get().uri("/one").exchange().expectStatus().isOk()
.get().uri("/one")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value().isEqualTo("one"); .expectBody(String.class).value().isEqualTo("one");
} }
@Test @Test
public void shouldFindController2() { public void shouldFindController2() {
this.webClient this.webClient.get().uri("/two").exchange().expectStatus().isOk()
.get().uri("/two")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value().isEqualTo("two"); .expectBody(String.class).value().isEqualTo("two");
} }
......
...@@ -51,4 +51,5 @@ public class WebFluxTestAutoConfigurationIntegrationTests { ...@@ -51,4 +51,5 @@ public class WebFluxTestAutoConfigurationIntegrationTests {
assertThat(this.applicationContext) assertThat(this.applicationContext)
.has(importedAutoConfiguration(ValidationAutoConfiguration.class)); .has(importedAutoConfiguration(ValidationAutoConfiguration.class));
} }
} }
...@@ -37,19 +37,13 @@ public class WebFluxTestOneControllerIntegrationTests { ...@@ -37,19 +37,13 @@ public class WebFluxTestOneControllerIntegrationTests {
@Test @Test
public void shouldFindController() { public void shouldFindController() {
this.webClient this.webClient.get().uri("/one").exchange().expectStatus().isOk()
.get().uri("/one")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value().isEqualTo("one"); .expectBody(String.class).value().isEqualTo("one");
} }
@Test @Test
public void shouldNotScanOtherController() { public void shouldNotScanOtherController() {
this.webClient this.webClient.get().uri("/two").exchange().expectStatus().isNotFound();
.get().uri("/two")
.exchange()
.expectStatus().isNotFound();
} }
} }
...@@ -46,19 +46,13 @@ public class WebTestClientSpringBootTestIntegrationTests { ...@@ -46,19 +46,13 @@ public class WebTestClientSpringBootTestIntegrationTests {
@Test @Test
public void shouldFindController1() { public void shouldFindController1() {
this.webClient this.webClient.get().uri("/one").exchange().expectStatus().isOk()
.get().uri("/one")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value().isEqualTo("one"); .expectBody(String.class).value().isEqualTo("one");
} }
@Test @Test
public void shouldFindController2() { public void shouldFindController2() {
this.webClient this.webClient.get().uri("/two").exchange().expectStatus().isOk()
.get().uri("/two")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value().isEqualTo("two"); .expectBody(String.class).value().isEqualTo("two");
} }
......
...@@ -35,13 +35,13 @@ class HateoasController { ...@@ -35,13 +35,13 @@ class HateoasController {
@RequestMapping("/resource") @RequestMapping("/resource")
public Resource<Map<String, String>> resource() { public Resource<Map<String, String>> resource() {
return new Resource<Map<String, String>>(new HashMap<String, String>(), return new Resource<>(new HashMap<String, String>(),
new Link("self", "http://api.example.com")); new Link("self", "http://api.example.com"));
} }
@RequestMapping("/plain") @RequestMapping("/plain")
public Map<String, String> plain() { public Map<String, String> plain() {
return new HashMap<String, String>(); return new HashMap<>();
} }
} }
...@@ -19,8 +19,8 @@ package org.springframework.boot.test.context; ...@@ -19,8 +19,8 @@ package org.springframework.boot.test.context;
import org.springframework.test.context.MergedContextConfiguration; import org.springframework.test.context.MergedContextConfiguration;
/** /**
* Encapsulates the <em>merged</em> context configuration declared on a test class and * Encapsulates the <em>merged</em> context configuration declared on a test class and all
* all of its superclasses for a reactive web application. * of its superclasses for a reactive web application.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 2.0.0 * @since 2.0.0
...@@ -31,4 +31,5 @@ public class ReactiveWebMergedContextConfiguration extends MergedContextConfigur ...@@ -31,4 +31,5 @@ public class ReactiveWebMergedContextConfiguration extends MergedContextConfigur
MergedContextConfiguration mergedConfig) { MergedContextConfiguration mergedConfig) {
super(mergedConfig); super(mergedConfig);
} }
} }
...@@ -115,8 +115,8 @@ public @interface SpringBootTest { ...@@ -115,8 +115,8 @@ public @interface SpringBootTest {
/** /**
* Creates a {@link WebApplicationContext} with a mock servlet environment if * Creates a {@link WebApplicationContext} with a mock servlet environment if
* servlet APIs are on the classpath, a {@link ReactiveWebApplicationContext} * servlet APIs are on the classpath, a {@link ReactiveWebApplicationContext} if
* if Spring WebFlux is on the classpath or a regular {@link ApplicationContext} * Spring WebFlux is on the classpath or a regular {@link ApplicationContext}
* otherwise. * otherwise.
*/ */
MOCK(false), MOCK(false),
......
...@@ -93,7 +93,8 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr ...@@ -93,7 +93,8 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
TestContext context = super.buildTestContext(); TestContext context = super.buildTestContext();
verifyConfiguration(context.getTestClass()); verifyConfiguration(context.getTestClass());
WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass()); WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass());
if (webEnvironment == WebEnvironment.MOCK && deduceWebApplication() == WebApplicationType.SERVLET) { if (webEnvironment == WebEnvironment.MOCK
&& deduceWebApplication() == WebApplicationType.SERVLET) {
context.setAttribute(ACTIVATE_SERVLET_LISTENER, true); context.setAttribute(ACTIVATE_SERVLET_LISTENER, true);
} }
else if (webEnvironment != null && webEnvironment.isEmbedded()) { else if (webEnvironment != null && webEnvironment.isEmbedded()) {
...@@ -154,8 +155,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr ...@@ -154,8 +155,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass()); WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass());
if (webEnvironment != null) { if (webEnvironment != null) {
WebApplicationType webApplicationType = getWebApplicationType(mergedConfig); WebApplicationType webApplicationType = getWebApplicationType(mergedConfig);
if (webApplicationType == WebApplicationType.SERVLET && if (webApplicationType == WebApplicationType.SERVLET
(webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) { && (webEnvironment.isEmbedded()
|| webEnvironment == WebEnvironment.MOCK)) {
WebAppConfiguration webAppConfiguration = AnnotatedElementUtils WebAppConfiguration webAppConfiguration = AnnotatedElementUtils
.findMergedAnnotation(mergedConfig.getTestClass(), .findMergedAnnotation(mergedConfig.getTestClass(),
WebAppConfiguration.class); WebAppConfiguration.class);
...@@ -164,8 +166,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr ...@@ -164,8 +166,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
mergedConfig = new WebMergedContextConfiguration(mergedConfig, mergedConfig = new WebMergedContextConfiguration(mergedConfig,
resourceBasePath); resourceBasePath);
} }
else if (webApplicationType == WebApplicationType.REACTIVE && else if (webApplicationType == WebApplicationType.REACTIVE
(webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) { && (webEnvironment.isEmbedded()
|| webEnvironment == WebEnvironment.MOCK)) {
return new ReactiveWebMergedContextConfiguration(mergedConfig); return new ReactiveWebMergedContextConfiguration(mergedConfig);
} }
} }
...@@ -174,8 +177,8 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr ...@@ -174,8 +177,8 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
private WebApplicationType getWebApplicationType( private WebApplicationType getWebApplicationType(
MergedContextConfiguration configuration) { MergedContextConfiguration configuration) {
WebApplicationType webApplicationType = WebApplicationType webApplicationType = getConfiguredWebApplicationType(
getConfiguredWebApplicationType(configuration); configuration);
if (webApplicationType != null) { if (webApplicationType != null) {
return webApplicationType; return webApplicationType;
} }
......
...@@ -42,8 +42,8 @@ class WebTestClientContextCustomizer implements ContextCustomizer { ...@@ -42,8 +42,8 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
@Override @Override
public void customizeContext(ConfigurableApplicationContext context, public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedConfig) { MergedContextConfiguration mergedConfig) {
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation( SpringBootTest annotation = AnnotatedElementUtils
mergedConfig.getTestClass(), SpringBootTest.class); .getMergedAnnotation(mergedConfig.getTestClass(), SpringBootTest.class);
if (annotation.webEnvironment().isEmbedded()) { if (annotation.webEnvironment().isEmbedded()) {
registerWebTestClient(context); registerWebTestClient(context);
} }
......
...@@ -32,8 +32,7 @@ import org.springframework.util.ClassUtils; ...@@ -32,8 +32,7 @@ import org.springframework.util.ClassUtils;
*/ */
public class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory { public class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory {
private static final String WEB_TEST_CLIENT_CLASS = private static final String WEB_TEST_CLIENT_CLASS = "org.springframework.web.reactive.function.client.WebClient";
"org.springframework.web.reactive.function.client.WebClient";
@Override @Override
public ContextCustomizer createContextCustomizer(Class<?> testClass, public ContextCustomizer createContextCustomizer(Class<?> testClass,
......
...@@ -62,19 +62,15 @@ public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests ...@@ -62,19 +62,15 @@ public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests
@Test @Test
public void runAndTestHttpEndpoint() { public void runAndTestHttpEndpoint() {
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
WebTestClient.bindToServer() WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build()
.baseUrl("http://localhost:" + this.port).build() .get().uri("/").exchange().expectBody(String.class).value()
.get().uri("/") .isEqualTo("Hello World");
.exchange()
.expectBody(String.class).value().isEqualTo("Hello World");
} }
@Test @Test
public void injectWebTestClient() { public void injectWebTestClient() {
this.webClient this.webClient.get().uri("/").exchange().expectBody(String.class).value()
.get().uri("/") .isEqualTo("Hello World");
.exchange()
.expectBody(String.class).value().isEqualTo("Hello World");
} }
@Test @Test
......
...@@ -38,10 +38,9 @@ public enum WebApplicationType { ...@@ -38,10 +38,9 @@ public enum WebApplicationType {
SERVLET, SERVLET,
/** /**
* The application should run as a reactive web application and should start * The application should run as a reactive web application and should start an
* an embedded web container. * embedded web container.
*/ */
REACTIVE; REACTIVE;
} }
...@@ -30,7 +30,8 @@ import org.springframework.util.Assert; ...@@ -30,7 +30,8 @@ import org.springframework.util.Assert;
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
*/ */
public class AbstractConfigurableReactiveWebServer implements ConfigurableReactiveWebServer { public class AbstractConfigurableReactiveWebServer
implements ConfigurableReactiveWebServer {
private int port = 8080; private int port = 8080;
...@@ -143,4 +144,5 @@ public class AbstractConfigurableReactiveWebServer implements ConfigurableReacti ...@@ -143,4 +144,5 @@ public class AbstractConfigurableReactiveWebServer implements ConfigurableReacti
public void setServerHeader(String serverHeader) { public void setServerHeader(String serverHeader) {
this.serverHeader = serverHeader; this.serverHeader = serverHeader;
} }
} }
...@@ -28,9 +28,8 @@ import org.apache.commons.logging.LogFactory; ...@@ -28,9 +28,8 @@ import org.apache.commons.logging.LogFactory;
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
*/ */
public abstract class AbstractReactiveWebServerFactory public abstract class AbstractReactiveWebServerFactory extends
extends AbstractConfigurableReactiveWebServer AbstractConfigurableReactiveWebServer implements ReactiveWebServerFactory {
implements ReactiveWebServerFactory {
protected final Log logger = LogFactory.getLog(getClass()); protected final Log logger = LogFactory.getLog(getClass());
...@@ -41,7 +40,6 @@ public abstract class AbstractReactiveWebServerFactory ...@@ -41,7 +40,6 @@ public abstract class AbstractReactiveWebServerFactory
super(port); super(port);
} }
/** /**
* Return the absolute temp dir for given web server. * Return the absolute temp dir for given web server.
* @param prefix servlet container name * @param prefix servlet container name
......
...@@ -37,7 +37,8 @@ import org.springframework.boot.web.servlet.ServletContextInitializer; ...@@ -37,7 +37,8 @@ import org.springframework.boot.web.servlet.ServletContextInitializer;
* @see EmbeddedServletContainerFactory * @see EmbeddedServletContainerFactory
* @see EmbeddedServletContainerCustomizer * @see EmbeddedServletContainerCustomizer
*/ */
public interface ConfigurableEmbeddedServletContainer extends ConfigurableEmbeddedWebServer { public interface ConfigurableEmbeddedServletContainer
extends ConfigurableEmbeddedWebServer {
/** /**
* Sets the context path for the embedded servlet container. The context should start * Sets the context path for the embedded servlet container. The context should start
......
...@@ -23,9 +23,8 @@ import org.springframework.boot.web.servlet.ErrorPage; ...@@ -23,9 +23,8 @@ import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.ErrorPageRegistry; import org.springframework.boot.web.servlet.ErrorPageRegistry;
/** /**
* Interface that regroups common customizations to * Interface that regroups common customizations to embedded server factories such as
* embedded server factories such as {@link EmbeddedServletContainerFactory} * {@link EmbeddedServletContainerFactory} and {@link ReactiveWebServerFactory}.
* and {@link ReactiveWebServerFactory}.
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
*/ */
......
...@@ -18,19 +18,19 @@ package org.springframework.boot.context.embedded; ...@@ -18,19 +18,19 @@ package org.springframework.boot.context.embedded;
/** /**
* Event to be published after the {@link EmbeddedReactiveWebApplicationContext} is * Event to be published after the {@link EmbeddedReactiveWebApplicationContext} is
* refreshed and the {@link EmbeddedWebServer} is ready. Useful for * refreshed and the {@link EmbeddedWebServer} is ready. Useful for obtaining the local
* obtaining the local port of a running server. * port of a running server.
* *
* @author Brian Clozel * @author Brian Clozel
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 2.0.0 * @since 2.0.0
*/ */
public class EmbeddedReactiveWebServerInitializedEvent extends EmbeddedWebServerInitializedEvent { public class EmbeddedReactiveWebServerInitializedEvent
extends EmbeddedWebServerInitializedEvent {
private final EmbeddedReactiveWebApplicationContext applicationContext; private final EmbeddedReactiveWebApplicationContext applicationContext;
public EmbeddedReactiveWebServerInitializedEvent( public EmbeddedReactiveWebServerInitializedEvent(EmbeddedWebServer source,
EmbeddedWebServer source,
EmbeddedReactiveWebApplicationContext applicationContext) { EmbeddedReactiveWebApplicationContext applicationContext) {
super(source); super(source);
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
...@@ -45,4 +45,5 @@ public class EmbeddedReactiveWebServerInitializedEvent extends EmbeddedWebServer ...@@ -45,4 +45,5 @@ public class EmbeddedReactiveWebServerInitializedEvent extends EmbeddedWebServer
public String getServerId() { public String getServerId() {
return "server"; return "server";
} }
} }
...@@ -19,23 +19,24 @@ package org.springframework.boot.context.embedded; ...@@ -19,23 +19,24 @@ package org.springframework.boot.context.embedded;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* Event to be published after the {@link EmbeddedWebApplicationContext} is * Event to be published after the {@link EmbeddedWebApplicationContext} is refreshed and
* refreshed and the {@link EmbeddedWebServer} is ready. Useful for * the {@link EmbeddedWebServer} is ready. Useful for obtaining the local port of a
* obtaining the local port of a running server. * running server.
* *
* <p>Normally it will have been started, but listeners are free to inspect * <p>
* the server and stop and start it if they want to. * Normally it will have been started, but listeners are free to inspect the server and
* stop and start it if they want to.
* *
* @author Dave Syer * @author Dave Syer
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class EmbeddedServletContainerInitializedEvent extends EmbeddedWebServerInitializedEvent { public class EmbeddedServletContainerInitializedEvent
extends EmbeddedWebServerInitializedEvent {
private final EmbeddedWebApplicationContext applicationContext; private final EmbeddedWebApplicationContext applicationContext;
public EmbeddedServletContainerInitializedEvent( public EmbeddedServletContainerInitializedEvent(
EmbeddedWebApplicationContext applicationContext, EmbeddedWebApplicationContext applicationContext, EmbeddedWebServer source) {
EmbeddedWebServer source) {
super(source); super(source);
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
......
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
package org.springframework.boot.context.embedded; package org.springframework.boot.context.embedded;
/** /**
* Simple interface that represents a fully configured embedded web server (for * Simple interface that represents a fully configured embedded web server (for example
* example Tomcat or Jetty). Allows the server to be {@link #start() started} and * Tomcat or Jetty). Allows the server to be {@link #start() started} and {@link #stop()
* {@link #stop() stopped}. * stopped}.
* <p> * <p>
* Instances of this class are usually obtained via a * Instances of this class are usually obtained via a
* {@link EmbeddedServletContainerFactory}. * {@link EmbeddedServletContainerFactory}.
...@@ -31,15 +31,15 @@ package org.springframework.boot.context.embedded; ...@@ -31,15 +31,15 @@ package org.springframework.boot.context.embedded;
public interface EmbeddedWebServer { public interface EmbeddedWebServer {
/** /**
* Starts the embedded web server. Calling this method on an already started * Starts the embedded web server. Calling this method on an already started container
* container has no effect. * has no effect.
* @throws EmbeddedWebServerException if the container cannot be started * @throws EmbeddedWebServerException if the container cannot be started
*/ */
void start() throws EmbeddedWebServerException; void start() throws EmbeddedWebServerException;
/** /**
* Stops the embedded web server. Calling this method on an already stopped * Stops the embedded web server. Calling this method on an already stopped container
* container has no effect. * has no effect.
* @throws EmbeddedWebServerException if the container cannot be stopped * @throws EmbeddedWebServerException if the container cannot be stopped
*/ */
void stop() throws EmbeddedWebServerException; void stop() throws EmbeddedWebServerException;
......
...@@ -20,9 +20,9 @@ import org.springframework.context.ApplicationContext; ...@@ -20,9 +20,9 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
/** /**
* Event to be published after the application context is * Event to be published after the application context is refreshed and the
* refreshed and the {@link EmbeddedWebServer} is ready. Useful for * {@link EmbeddedWebServer} is ready. Useful for obtaining the local port of a running
* obtaining the local port of a running server. * server.
* *
* @author Brian Clozel * @author Brian Clozel
* @author Stephane Nicoll * @author Stephane Nicoll
...@@ -63,8 +63,8 @@ public abstract class EmbeddedWebServerInitializedEvent extends ApplicationEvent ...@@ -63,8 +63,8 @@ public abstract class EmbeddedWebServerInitializedEvent extends ApplicationEvent
} }
/** /**
* Access the {@link EmbeddedWebServer} Id used internally * Access the {@link EmbeddedWebServer} Id used internally to differentiate
* to differentiate application / management servers. * application / management servers.
* @return the server internal Id * @return the server internal Id
*/ */
public abstract String getServerId(); public abstract String getServerId();
......
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
package org.springframework.boot.context.embedded; package org.springframework.boot.context.embedded;
/** /**
* Strategy interface for customizing auto-configured embedded reactive servers. Any * Strategy interface for customizing auto-configured embedded reactive servers. Any beans
* beans of this type will get a callback with the server factory before the server * of this type will get a callback with the server factory before the server itself is
* itself is started, so you can set the port, address, error pages etc. * started, so you can set the port, address, error pages etc.
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
*/ */
......
...@@ -29,8 +29,8 @@ import org.springframework.beans.factory.config.BeanPostProcessor; ...@@ -29,8 +29,8 @@ import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/** /**
* {@link BeanPostProcessor} that applies all {@link ReactiveWebServerCustomizer}s * {@link BeanPostProcessor} that applies all {@link ReactiveWebServerCustomizer}s from
* from the bean factory to {@link ConfigurableReactiveWebServer} beans. * the bean factory to {@link ConfigurableReactiveWebServer} beans.
* *
* @author Brian Clozel * @author Brian Clozel
* @author Stephane Nicoll * @author Stephane Nicoll
...@@ -63,8 +63,7 @@ public class ReactiveWebServerCustomizerBeanPostProcessor ...@@ -63,8 +63,7 @@ public class ReactiveWebServerCustomizerBeanPostProcessor
return bean; return bean;
} }
private void postProcessBeforeInitialization( private void postProcessBeforeInitialization(ConfigurableReactiveWebServer bean) {
ConfigurableReactiveWebServer bean) {
for (ReactiveWebServerCustomizer customizer : getCustomizers()) { for (ReactiveWebServerCustomizer customizer : getCustomizers()) {
customizer.customize(bean); customizer.customize(bean);
} }
...@@ -73,10 +72,8 @@ public class ReactiveWebServerCustomizerBeanPostProcessor ...@@ -73,10 +72,8 @@ public class ReactiveWebServerCustomizerBeanPostProcessor
private Collection<ReactiveWebServerCustomizer> getCustomizers() { private Collection<ReactiveWebServerCustomizer> getCustomizers() {
if (this.customizers == null) { if (this.customizers == null) {
// Look up does not include the parent context // Look up does not include the parent context
this.customizers = new ArrayList<ReactiveWebServerCustomizer>( this.customizers = new ArrayList<ReactiveWebServerCustomizer>(this.beanFactory
this.beanFactory .getBeansOfType(ReactiveWebServerCustomizer.class, false, false)
.getBeansOfType(ReactiveWebServerCustomizer.class,
false, false)
.values()); .values());
Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE); Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
this.customizers = Collections.unmodifiableList(this.customizers); this.customizers = Collections.unmodifiableList(this.customizers);
......
...@@ -31,8 +31,8 @@ import org.springframework.http.server.reactive.HttpHandler; ...@@ -31,8 +31,8 @@ import org.springframework.http.server.reactive.HttpHandler;
public interface ReactiveWebServerFactory { public interface ReactiveWebServerFactory {
/** /**
* Gets a new fully configured but paused {@link EmbeddedWebServer} instance. * Gets a new fully configured but paused {@link EmbeddedWebServer} instance. Clients
* Clients should not be able to connect to the returned server until * should not be able to connect to the returned server until
* {@link EmbeddedWebServer#start()} is called (which happens when the * {@link EmbeddedWebServer#start()} is called (which happens when the
* {@link ApplicationContext} has been fully refreshed). * {@link ApplicationContext} has been fully refreshed).
* @param httpHandler the HTTP handler in charge of processing requests * @param httpHandler the HTTP handler in charge of processing requests
...@@ -43,10 +43,10 @@ public interface ReactiveWebServerFactory { ...@@ -43,10 +43,10 @@ public interface ReactiveWebServerFactory {
/** /**
* Register a map of {@link HttpHandler}s, each to a specific context path. * Register a map of {@link HttpHandler}s, each to a specific context path.
*
* @param handlerMap a map of context paths and the associated {@code HttpHandler} * @param handlerMap a map of context paths and the associated {@code HttpHandler}
* @return a fully configured and started {@link EmbeddedWebServer} * @return a fully configured and started {@link EmbeddedWebServer}
* @see EmbeddedWebServer#stop() * @see EmbeddedWebServer#stop()
*/ */
EmbeddedWebServer getReactiveHttpServer(Map<String, HttpHandler> handlerMap); EmbeddedWebServer getReactiveHttpServer(Map<String, HttpHandler> handlerMap);
} }
...@@ -32,8 +32,8 @@ import org.springframework.core.env.PropertySource; ...@@ -32,8 +32,8 @@ import org.springframework.core.env.PropertySource;
/** /**
* {@link ApplicationContextInitializer} that sets {@link Environment} properties for the * {@link ApplicationContextInitializer} that sets {@link Environment} properties for the
* ports that {@link EmbeddedWebServer} servers are actually listening on. The * ports that {@link EmbeddedWebServer} servers are actually listening on. The property
* property {@literal "local.server.port"} can be injected directly into tests using * {@literal "local.server.port"} can be injected directly into tests using
* {@link Value @Value} or obtained via the {@link Environment}. * {@link Value @Value} or obtained via the {@link Environment}.
* <p> * <p>
* If the {@link EmbeddedWebApplicationContext} has a * If the {@link EmbeddedWebApplicationContext} has a
...@@ -71,7 +71,6 @@ public class ServerPortInfoApplicationContextInitializer ...@@ -71,7 +71,6 @@ public class ServerPortInfoApplicationContextInitializer
event.getEmbeddedWebServer().getPort()); event.getEmbeddedWebServer().getPort());
} }
private void setPortProperty(ApplicationContext context, String propertyName, private void setPortProperty(ApplicationContext context, String propertyName,
int port) { int port) {
if (context instanceof ConfigurableApplicationContext) { if (context instanceof ConfigurableApplicationContext) {
......
...@@ -35,8 +35,7 @@ import org.springframework.http.server.reactive.HttpHandler; ...@@ -35,8 +35,7 @@ import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.JettyHttpHandlerAdapter; import org.springframework.http.server.reactive.JettyHttpHandlerAdapter;
/** /**
* {@link ReactiveWebServerFactory} that can be used to create * {@link ReactiveWebServerFactory} that can be used to create {@link JettyWebServer}s.
* {@link JettyWebServer}s.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
...@@ -90,8 +89,8 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact ...@@ -90,8 +89,8 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact
Server server = new Server(getThreadPool()); Server server = new Server(getThreadPool());
server.addConnector(createConnector(address, server)); server.addConnector(createConnector(address, server));
ServletHolder servletHolder = new ServletHolder(servlet); ServletHolder servletHolder = new ServletHolder(servlet);
ServletContextHandler contextHandler = new ServletContextHandler(server, ServletContextHandler contextHandler = new ServletContextHandler(server, "",
"", false, false); false, false);
contextHandler.addServlet(servletHolder, "/"); contextHandler.addServlet(servletHolder, "/");
this.logger.info("Server initialized with port: " + port); this.logger.info("Server initialized with port: " + port);
return server; return server;
......
...@@ -36,9 +36,9 @@ import org.springframework.util.ReflectionUtils; ...@@ -36,9 +36,9 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* {@link EmbeddedWebServer} that can be used to control a Jetty web server. * {@link EmbeddedWebServer} that can be used to control a Jetty web server. Usually this
* Usually this class should be created using the * class should be created using the {@link JettyReactiveWebServerFactory} and not
* {@link JettyReactiveWebServerFactory} and not directly. * directly.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Dave Syer * @author Dave Syer
...@@ -49,8 +49,7 @@ import org.springframework.util.StringUtils; ...@@ -49,8 +49,7 @@ import org.springframework.util.StringUtils;
*/ */
public class JettyWebServer implements EmbeddedWebServer { public class JettyWebServer implements EmbeddedWebServer {
private static final Log logger = LogFactory private static final Log logger = LogFactory.getLog(JettyWebServer.class);
.getLog(JettyWebServer.class);
private final Object monitor = new Object(); private final Object monitor = new Object();
...@@ -233,4 +232,5 @@ public class JettyWebServer implements EmbeddedWebServer { ...@@ -233,4 +232,5 @@ public class JettyWebServer implements EmbeddedWebServer {
public Server getServer() { public Server getServer() {
return this.server; return this.server;
} }
} }
...@@ -32,7 +32,8 @@ import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; ...@@ -32,7 +32,8 @@ import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
public class ReactorNettyReactiveWebServerFactory extends AbstractReactiveWebServerFactory { public class ReactorNettyReactiveWebServerFactory
extends AbstractReactiveWebServerFactory {
public ReactorNettyReactiveWebServerFactory() { public ReactorNettyReactiveWebServerFactory() {
} }
...@@ -44,14 +45,16 @@ public class ReactorNettyReactiveWebServerFactory extends AbstractReactiveWebSer ...@@ -44,14 +45,16 @@ public class ReactorNettyReactiveWebServerFactory extends AbstractReactiveWebSer
@Override @Override
public EmbeddedWebServer getReactiveHttpServer(HttpHandler httpHandler) { public EmbeddedWebServer getReactiveHttpServer(HttpHandler httpHandler) {
HttpServer server = createHttpServer(); HttpServer server = createHttpServer();
ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler); ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(
httpHandler);
return new ReactorNettyWebServer(server, handlerAdapter); return new ReactorNettyWebServer(server, handlerAdapter);
} }
@Override @Override
public EmbeddedWebServer getReactiveHttpServer(Map<String, HttpHandler> handlerMap) { public EmbeddedWebServer getReactiveHttpServer(Map<String, HttpHandler> handlerMap) {
HttpServer server = createHttpServer(); HttpServer server = createHttpServer();
ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(handlerMap); ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(
handlerMap);
return new ReactorNettyWebServer(server, handlerAdapter); return new ReactorNettyWebServer(server, handlerAdapter);
} }
......
...@@ -44,7 +44,8 @@ public class ReactorNettyWebServer implements EmbeddedWebServer, Loopback { ...@@ -44,7 +44,8 @@ public class ReactorNettyWebServer implements EmbeddedWebServer, Loopback {
private AtomicReference<NettyContext> nettyContext = new AtomicReference<>(); private AtomicReference<NettyContext> nettyContext = new AtomicReference<>();
public ReactorNettyWebServer(HttpServer reactorServer, ReactorHttpHandlerAdapter handlerAdapter) { public ReactorNettyWebServer(HttpServer reactorServer,
ReactorHttpHandlerAdapter handlerAdapter) {
this.reactorServer = reactorServer; this.reactorServer = reactorServer;
this.handlerAdapter = handlerAdapter; this.handlerAdapter = handlerAdapter;
} }
...@@ -62,20 +63,24 @@ public class ReactorNettyWebServer implements EmbeddedWebServer, Loopback { ...@@ -62,20 +63,24 @@ public class ReactorNettyWebServer implements EmbeddedWebServer, Loopback {
@Override @Override
public void start() throws EmbeddedWebServerException { public void start() throws EmbeddedWebServerException {
if (this.nettyContext.get() == null) { if (this.nettyContext.get() == null) {
this.nettyContext.set(this.reactorServer.newHandler(this.handlerAdapter).block()); this.nettyContext
.set(this.reactorServer.newHandler(this.handlerAdapter).block());
startDaemonAwaitThread(); startDaemonAwaitThread();
} }
} }
private void startDaemonAwaitThread() { private void startDaemonAwaitThread() {
Thread awaitThread = new Thread("server") { Thread awaitThread = new Thread("server") {
@Override @Override
public void run() { public void run() {
try { try {
ReactorNettyWebServer.latch.await(); ReactorNettyWebServer.latch.await();
} }
catch (InterruptedException e) { } catch (InterruptedException e) {
}
} }
}; };
awaitThread.setContextClassLoader(getClass().getClassLoader()); awaitThread.setContextClassLoader(getClass().getClassLoader());
awaitThread.setDaemon(false); awaitThread.setDaemon(false);
...@@ -98,4 +103,5 @@ public class ReactorNettyWebServer implements EmbeddedWebServer, Loopback { ...@@ -98,4 +103,5 @@ public class ReactorNettyWebServer implements EmbeddedWebServer, Loopback {
} }
return 0; return 0;
} }
} }
...@@ -35,8 +35,7 @@ import org.springframework.util.ClassUtils; ...@@ -35,8 +35,7 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* {@link ReactiveWebServerFactory} that can be used to create * {@link ReactiveWebServerFactory} that can be used to create {@link TomcatWebServer}s.
* {@link TomcatWebServer}s.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
...@@ -93,7 +92,6 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac ...@@ -93,7 +92,6 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac
return tomcat; return tomcat;
} }
protected void prepareContext(Host host, TomcatHttpHandlerAdapter servlet) { protected void prepareContext(Host host, TomcatHttpHandlerAdapter servlet) {
File docBase = createTempDir("tomcat-docbase"); File docBase = createTempDir("tomcat-docbase");
TomcatEmbeddedContext context = new TomcatEmbeddedContext(); TomcatEmbeddedContext context = new TomcatEmbeddedContext();
...@@ -110,7 +108,6 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac ...@@ -110,7 +108,6 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac
host.addChild(context); host.addChild(context);
} }
// Needs to be protected so it can be used by subclasses // Needs to be protected so it can be used by subclasses
protected void customizeConnector(Connector connector) { protected void customizeConnector(Connector connector) {
int port = (getPort() >= 0 ? getPort() : 0); int port = (getPort() >= 0 ? getPort() : 0);
......
...@@ -39,15 +39,14 @@ import org.springframework.boot.context.embedded.EmbeddedWebServerException; ...@@ -39,15 +39,14 @@ import org.springframework.boot.context.embedded.EmbeddedWebServerException;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* {@link EmbeddedWebServer} that can be used to control a Tomcat web server. * {@link EmbeddedWebServer} that can be used to control a Tomcat web server. Usually this
* Usually this class should be created using the * class should be created using the {@link TomcatReactiveWebServerFactory} and not
* {@link TomcatReactiveWebServerFactory} and not directly. * directly.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
public class TomcatWebServer implements EmbeddedWebServer { public class TomcatWebServer implements EmbeddedWebServer {
private static final Log logger = LogFactory private static final Log logger = LogFactory
.getLog(TomcatEmbeddedServletContainer.class); .getLog(TomcatEmbeddedServletContainer.class);
...@@ -110,8 +109,8 @@ public class TomcatWebServer implements EmbeddedWebServer { ...@@ -110,8 +109,8 @@ public class TomcatWebServer implements EmbeddedWebServer {
startDaemonAwaitThread(); startDaemonAwaitThread();
} }
catch (Exception ex) { catch (Exception ex) {
throw new EmbeddedWebServerException( throw new EmbeddedWebServerException("Unable to start embedded Tomcat",
"Unable to start embedded Tomcat", ex); ex);
} }
} }
} }
...@@ -276,8 +275,8 @@ public class TomcatWebServer implements EmbeddedWebServer { ...@@ -276,8 +275,8 @@ public class TomcatWebServer implements EmbeddedWebServer {
} }
} }
catch (Exception ex) { catch (Exception ex) {
throw new EmbeddedWebServerException( throw new EmbeddedWebServerException("Unable to stop embedded Tomcat",
"Unable to stop embedded Tomcat", ex); ex);
} }
finally { finally {
containerCounter.decrementAndGet(); containerCounter.decrementAndGet();
......
...@@ -54,8 +54,8 @@ import org.springframework.util.ReflectionUtils; ...@@ -54,8 +54,8 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* {@link EmbeddedWebServer} that can be used to control an embedded Undertow * {@link EmbeddedWebServer} that can be used to control an embedded Undertow server.
* server. Typically this class should be created using * Typically this class should be created using
* {@link UndertowEmbeddedServletContainerFactory} and not directly. * {@link UndertowEmbeddedServletContainerFactory} and not directly.
* *
* @author Ivan Sopov * @author Ivan Sopov
...@@ -169,8 +169,8 @@ public class UndertowEmbeddedServletContainer implements EmbeddedWebServer { ...@@ -169,8 +169,8 @@ public class UndertowEmbeddedServletContainer implements EmbeddedWebServer {
failedPorts.iterator().next().getNumber()); failedPorts.iterator().next().getNumber());
} }
} }
throw new EmbeddedWebServerException( throw new EmbeddedWebServerException("Unable to start embedded Undertow",
"Unable to start embedded Undertow", ex); ex);
} }
} }
} }
...@@ -317,8 +317,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedWebServer { ...@@ -317,8 +317,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedWebServer {
this.undertow.stop(); this.undertow.stop();
} }
catch (Exception ex) { catch (Exception ex) {
throw new EmbeddedWebServerException("Unable to stop undertow", throw new EmbeddedWebServerException("Unable to stop undertow", ex);
ex);
} }
} }
} }
......
...@@ -27,8 +27,7 @@ import org.springframework.http.server.reactive.HttpHandler; ...@@ -27,8 +27,7 @@ import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.UndertowHttpHandlerAdapter; import org.springframework.http.server.reactive.UndertowHttpHandlerAdapter;
/** /**
* {@link ReactiveWebServerFactory} that can be used to create * {@link ReactiveWebServerFactory} that can be used to create {@link UndertowWebServer}s.
* {@link UndertowWebServer}s.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
...@@ -49,8 +48,8 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -49,8 +48,8 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
} }
/** /**
* Create a new {@link UndertowReactiveWebServerFactory} that listens for * Create a new {@link UndertowReactiveWebServerFactory} that listens for requests
* requests using the specified port. * using the specified port.
* @param port the port to listen on * @param port the port to listen on
*/ */
public UndertowReactiveWebServerFactory(int port) { public UndertowReactiveWebServerFactory(int port) {
...@@ -97,4 +96,5 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -97,4 +96,5 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
} }
return getAddress().getHostAddress(); return getAddress().getHostAddress();
} }
} }
...@@ -35,9 +35,9 @@ import org.springframework.util.ReflectionUtils; ...@@ -35,9 +35,9 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* {@link EmbeddedWebServer} that can be used to control a Jetty web server. * {@link EmbeddedWebServer} that can be used to control a Jetty web server. Usually this
* Usually this class should be created using the * class should be created using the {@link UndertowReactiveWebServerFactory} and not
* {@link UndertowReactiveWebServerFactory} and not directly. * directly.
* *
* @author Ivan Sopov * @author Ivan Sopov
* @author Andy Wilkinson * @author Andy Wilkinson
...@@ -98,8 +98,8 @@ public class UndertowWebServer implements EmbeddedWebServer { ...@@ -98,8 +98,8 @@ public class UndertowWebServer implements EmbeddedWebServer {
failedPorts.iterator().next().getNumber()); failedPorts.iterator().next().getNumber());
} }
} }
throw new EmbeddedWebServerException( throw new EmbeddedWebServerException("Unable to start embedded Undertow",
"Unable to start embedded Undertow", ex); ex);
} }
} }
} }
...@@ -141,7 +141,6 @@ public class UndertowWebServer implements EmbeddedWebServer { ...@@ -141,7 +141,6 @@ public class UndertowWebServer implements EmbeddedWebServer {
return ports; return ports;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private List<BoundChannel> extractChannels() { private List<BoundChannel> extractChannels() {
Field channelsField = ReflectionUtils.findField(Undertow.class, "channels"); Field channelsField = ReflectionUtils.findField(Undertow.class, "channels");
...@@ -155,7 +154,8 @@ public class UndertowWebServer implements EmbeddedWebServer { ...@@ -155,7 +154,8 @@ public class UndertowWebServer implements EmbeddedWebServer {
if (socketAddress instanceof InetSocketAddress) { if (socketAddress instanceof InetSocketAddress) {
String protocol = ReflectionUtils.findField(channel.getClass(), "ssl") != null String protocol = ReflectionUtils.findField(channel.getClass(), "ssl") != null
? "https" : "http"; ? "https" : "http";
return new UndertowWebServer.Port(((InetSocketAddress) socketAddress).getPort(), protocol); return new UndertowWebServer.Port(
((InetSocketAddress) socketAddress).getPort(), protocol);
} }
return null; return null;
} }
...@@ -190,7 +190,6 @@ public class UndertowWebServer implements EmbeddedWebServer { ...@@ -190,7 +190,6 @@ public class UndertowWebServer implements EmbeddedWebServer {
return new UndertowWebServer.Port(port, protocol); return new UndertowWebServer.Port(port, protocol);
} }
@Override @Override
public void stop() throws EmbeddedWebServerException { public void stop() throws EmbeddedWebServerException {
synchronized (this.monitor) { synchronized (this.monitor) {
...@@ -202,8 +201,7 @@ public class UndertowWebServer implements EmbeddedWebServer { ...@@ -202,8 +201,7 @@ public class UndertowWebServer implements EmbeddedWebServer {
this.undertow.stop(); this.undertow.stop();
} }
catch (Exception ex) { catch (Exception ex) {
throw new EmbeddedWebServerException("Unable to stop undertow", throw new EmbeddedWebServerException("Unable to stop undertow", ex);
ex);
} }
} }
} }
...@@ -264,4 +262,5 @@ public class UndertowWebServer implements EmbeddedWebServer { ...@@ -264,4 +262,5 @@ public class UndertowWebServer implements EmbeddedWebServer {
} }
} }
} }
...@@ -403,10 +403,12 @@ public class SpringApplicationTests { ...@@ -403,10 +403,12 @@ public class SpringApplicationTests {
@Test @Test
public void defaultApplicationContextForReactiveWeb() throws Exception { public void defaultApplicationContextForReactiveWeb() throws Exception {
SpringApplication application = new SpringApplication(ExampleReactiveWebConfig.class); SpringApplication application = new SpringApplication(
ExampleReactiveWebConfig.class);
application.setWebApplicationType(WebApplicationType.REACTIVE); application.setWebApplicationType(WebApplicationType.REACTIVE);
this.context = application.run(); this.context = application.run();
assertThat(this.context).isInstanceOf(EmbeddedReactiveWebApplicationContext.class); assertThat(this.context)
.isInstanceOf(EmbeddedReactiveWebApplicationContext.class);
} }
@Test @Test
...@@ -574,7 +576,7 @@ public class SpringApplicationTests { ...@@ -574,7 +576,7 @@ public class SpringApplicationTests {
@Test @Test
public void loadSources() throws Exception { public void loadSources() throws Exception {
Object[] sources = {ExampleConfig.class, "a", TestCommandLineRunner.class}; Object[] sources = { ExampleConfig.class, "a", TestCommandLineRunner.class };
TestSpringApplication application = new TestSpringApplication(sources); TestSpringApplication application = new TestSpringApplication(sources);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
application.setUseMockLoader(true); application.setUseMockLoader(true);
...@@ -586,7 +588,7 @@ public class SpringApplicationTests { ...@@ -586,7 +588,7 @@ public class SpringApplicationTests {
@Test @Test
public void wildcardSources() { public void wildcardSources() {
Object[] sources = { Object[] sources = {
"classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml"}; "classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml" };
TestSpringApplication application = new TestSpringApplication(sources); TestSpringApplication application = new TestSpringApplication(sources);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run(); this.context = application.run();
...@@ -601,7 +603,7 @@ public class SpringApplicationTests { ...@@ -601,7 +603,7 @@ public class SpringApplicationTests {
@Test @Test
public void runComponents() throws Exception { public void runComponents() throws Exception {
this.context = SpringApplication.run( this.context = SpringApplication.run(
new Object[] {ExampleWebConfig.class, Object.class}, new String[0]); new Object[] { ExampleWebConfig.class, Object.class }, new String[0]);
assertThat(this.context).isNotNull(); assertThat(this.context).isNotNull();
} }
...@@ -716,7 +718,7 @@ public class SpringApplicationTests { ...@@ -716,7 +718,7 @@ public class SpringApplicationTests {
public void defaultCommandLineArgs() throws Exception { public void defaultCommandLineArgs() throws Exception {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setDefaultProperties(StringUtils.splitArrayElementsIntoProperties( application.setDefaultProperties(StringUtils.splitArrayElementsIntoProperties(
new String[] {"baz=", "bar=spam"}, "=")); new String[] { "baz=", "bar=spam" }, "="));
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run("--bar=foo", "bucket", "crap"); this.context = application.run("--bar=foo", "bucket", "crap");
assertThat(this.context).isInstanceOf(AnnotationConfigApplicationContext.class); assertThat(this.context).isInstanceOf(AnnotationConfigApplicationContext.class);
...@@ -1046,7 +1048,6 @@ public class SpringApplicationTests { ...@@ -1046,7 +1048,6 @@ public class SpringApplicationTests {
} }
@Configuration @Configuration
static class FailingConfig { static class FailingConfig {
......
...@@ -55,7 +55,6 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -55,7 +55,6 @@ public abstract class AbstractReactiveWebServerFactoryTests {
protected EmbeddedWebServer webServer; protected EmbeddedWebServer webServer;
@After @After
public void tearDown() { public void tearDown() {
if (this.webServer != null) { if (this.webServer != null) {
...@@ -74,21 +73,17 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -74,21 +73,17 @@ public abstract class AbstractReactiveWebServerFactoryTests {
public void startStopServer() { public void startStopServer() {
this.webServer = getFactory().getReactiveHttpServer(new EchoHandler()); this.webServer = getFactory().getReactiveHttpServer(new EchoHandler());
this.webServer.start(); this.webServer.start();
Mono<String> result = getWebClient() Mono<String> result = getWebClient().post().uri("/test")
.post().uri("/test")
.contentType(MediaType.TEXT_PLAIN) .contentType(MediaType.TEXT_PLAIN)
.exchange(BodyInserters.fromObject("Hello World")) .exchange(BodyInserters.fromObject("Hello World"))
.then(response -> response.bodyToMono(String.class)); .then(response -> response.bodyToMono(String.class));
assertThat(result.block()).isEqualTo("Hello World"); assertThat(result.block()).isEqualTo("Hello World");
this.webServer.stop(); this.webServer.stop();
Mono<ClientResponse> response = getWebClient() Mono<ClientResponse> response = getWebClient().post().uri("/test")
.post().uri("/test")
.contentType(MediaType.TEXT_PLAIN) .contentType(MediaType.TEXT_PLAIN)
.exchange(BodyInserters.fromObject("Hello World")); .exchange(BodyInserters.fromObject("Hello World"));
StepVerifier.create(response) StepVerifier.create(response).expectError().verify();
.expectError()
.verify();
} }
@Test @Test
...@@ -99,9 +94,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -99,9 +94,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
this.webServer = factory.getReactiveHttpServer(new EchoHandler()); this.webServer = factory.getReactiveHttpServer(new EchoHandler());
this.webServer.start(); this.webServer.start();
Mono<String> result = WebClient.create("http://localhost:" + specificPort) Mono<String> result = WebClient.create("http://localhost:" + specificPort).post()
.post().uri("/test") .uri("/test").contentType(MediaType.TEXT_PLAIN)
.contentType(MediaType.TEXT_PLAIN)
.exchange(BodyInserters.fromObject("Hello World")) .exchange(BodyInserters.fromObject("Hello World"))
.then(response -> response.bodyToMono(String.class)); .then(response -> response.bodyToMono(String.class));
...@@ -120,4 +114,5 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -120,4 +114,5 @@ public abstract class AbstractReactiveWebServerFactoryTests {
return response.writeWith(request.getBody()); return response.writeWith(request.getBody());
} }
} }
} }
...@@ -20,15 +20,16 @@ import org.springframework.boot.context.embedded.AbstractReactiveWebServerFactor ...@@ -20,15 +20,16 @@ import org.springframework.boot.context.embedded.AbstractReactiveWebServerFactor
import org.springframework.boot.context.embedded.AbstractReactiveWebServerFactoryTests; import org.springframework.boot.context.embedded.AbstractReactiveWebServerFactoryTests;
/** /**
* Tests for {@link JettyReactiveWebServerFactory} and * Tests for {@link JettyReactiveWebServerFactory} and {@link JettyWebServer}.
* {@link JettyWebServer}.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { public class JettyReactiveWebServerFactoryTests
extends AbstractReactiveWebServerFactoryTests {
@Override @Override
protected AbstractReactiveWebServerFactory getFactory() { protected AbstractReactiveWebServerFactory getFactory() {
return new JettyReactiveWebServerFactory(0); return new JettyReactiveWebServerFactory(0);
} }
} }
...@@ -25,7 +25,8 @@ import org.springframework.boot.context.embedded.AbstractReactiveWebServerFactor ...@@ -25,7 +25,8 @@ import org.springframework.boot.context.embedded.AbstractReactiveWebServerFactor
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
public class ReactorNettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { public class ReactorNettyReactiveWebServerFactoryTests
extends AbstractReactiveWebServerFactoryTests {
@Override @Override
protected AbstractReactiveWebServerFactory getFactory() { protected AbstractReactiveWebServerFactory getFactory() {
......
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