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

Polish formatting

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