This commit is contained in:
Phillip Webb 2018-01-03 11:41:27 -08:00
parent 6bac365a72
commit bee5fa7fc6
24 changed files with 334 additions and 253 deletions

View File

@ -37,9 +37,11 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** /**
* {@link EnableAutoConfiguration Auto-configuration} for Cloud Foundry Health endpoint extensions. * {@link EnableAutoConfiguration Auto-configuration} for Cloud Foundry Health endpoint
* extensions.
* *
* @author Madhura Bhave * @author Madhura Bhave
* @since 2.0.0
*/ */
@Configuration @Configuration
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)

View File

@ -70,7 +70,8 @@ public class WebMvcEndpointCorsIntegrationTests {
createMockMvc() createMockMvc()
.perform(options("/actuator/beans").header("Origin", "foo.example.com") .perform(options("/actuator/beans").header("Origin", "foo.example.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); .andExpect(
header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
} }
@Test @Test

View File

@ -217,10 +217,11 @@ public class AutoConfigurationImportSelector
private List<String> getExcludeAutoConfigurationsProperty() { private List<String> getExcludeAutoConfigurationsProperty() {
if (getEnvironment() instanceof ConfigurableEnvironment) { if (getEnvironment() instanceof ConfigurableEnvironment) {
Binder binder = Binder.get(getEnvironment()); Binder binder = Binder.get(getEnvironment());
return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(Arrays::asList) return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class)
.orElse(Collections.emptyList()); .map(Arrays::asList).orElse(Collections.emptyList());
} }
String[] excludes = getEnvironment().getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class); String[] excludes = getEnvironment()
.getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class);
return (excludes == null ? Collections.emptyList() : Arrays.asList(excludes)); return (excludes == null ? Collections.emptyList() : Arrays.asList(excludes));
} }

View File

@ -487,8 +487,8 @@ public class ResourceProperties {
return CacheControl.noCache(); return CacheControl.noCache();
} }
if (this.maxAge != null) { if (this.maxAge != null) {
return CacheControl return CacheControl.maxAge(this.maxAge.getSeconds(),
.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS); TimeUnit.SECONDS);
} }
return CacheControl.empty(); return CacheControl.empty();
} }

View File

@ -390,15 +390,13 @@ public class DefaultServletWebServerFactoryCustomizer
} }
private static void customizeRedirectContextRoot( private static void customizeRedirectContextRoot(
TomcatServletWebServerFactory factory, TomcatServletWebServerFactory factory, boolean redirectContextRoot) {
boolean redirectContextRoot) {
factory.addContextCustomizers((context) -> context factory.addContextCustomizers((context) -> context
.setMapperContextRootRedirectEnabled(redirectContextRoot)); .setMapperContextRootRedirectEnabled(redirectContextRoot));
} }
private static void customizeUseRelativeRedirects( private static void customizeUseRelativeRedirects(
TomcatServletWebServerFactory factory, TomcatServletWebServerFactory factory, boolean useRelativeRedirects) {
boolean useRelativeRedirects) {
factory.addContextCustomizers( factory.addContextCustomizers(
(context) -> context.setUseRelativeRedirects(useRelativeRedirects)); (context) -> context.setUseRelativeRedirects(useRelativeRedirects));
} }

View File

@ -36,8 +36,8 @@ import org.springframework.web.servlet.mvc.ParameterizableViewController;
/** /**
* An {@link AbstractUrlHandlerMapping} for an application's welcome page. Supports both * An {@link AbstractUrlHandlerMapping} for an application's welcome page. Supports both
* static and templated files. If both a static and templated index page are available, the * static and templated files. If both a static and templated index page are available,
* static page is preferred. * the static page is preferred.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Bruce Brouwer * @author Bruce Brouwer
@ -46,7 +46,8 @@ final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping {
private static final Log logger = LogFactory.getLog(WelcomePageHandlerMapping.class); private static final Log logger = LogFactory.getLog(WelcomePageHandlerMapping.class);
private static final List<MediaType> MEDIA_TYPES_ALL = Collections.singletonList(MediaType.ALL); private static final List<MediaType> MEDIA_TYPES_ALL = Collections
.singletonList(MediaType.ALL);
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, ApplicationContext applicationContext, Optional<Resource> welcomePage,

View File

@ -106,7 +106,8 @@ public class SpringDataWebAutoConfigurationTests {
load(); load();
PageableHandlerMethodArgumentResolver argumentResolver = this.context PageableHandlerMethodArgumentResolver argumentResolver = this.context
.getBean(PageableHandlerMethodArgumentResolver.class); .getBean(PageableHandlerMethodArgumentResolver.class);
SpringDataWebProperties.Pageable properties = new SpringDataWebProperties().getPageable(); SpringDataWebProperties.Pageable properties = new SpringDataWebProperties()
.getPageable();
assertThat(ReflectionTestUtils.getField(argumentResolver, "pageParameterName")) assertThat(ReflectionTestUtils.getField(argumentResolver, "pageParameterName"))
.isEqualTo(properties.getPageParameter()); .isEqualTo(properties.getPageParameter());
assertThat(ReflectionTestUtils.getField(argumentResolver, "sizeParameterName")) assertThat(ReflectionTestUtils.getField(argumentResolver, "sizeParameterName"))

View File

@ -69,46 +69,53 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
@Test @Test
public void customPrefix() { public void customPrefix() {
this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/").run(context -> { this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/")
MockServerWebExchange exchange = render(context, "prefixed"); .run(context -> {
String result = exchange.getResponse().getBodyAsString().block(); MockServerWebExchange exchange = render(context, "prefixed");
assertThat(result).contains("prefixed"); String result = exchange.getResponse().getBodyAsString().block();
}); assertThat(result).contains("prefixed");
});
} }
@Test @Test
public void customSuffix() { public void customSuffix() {
this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker").run(context -> { this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker")
MockServerWebExchange exchange = render(context, "suffixed"); .run(context -> {
String result = exchange.getResponse().getBodyAsString().block(); MockServerWebExchange exchange = render(context, "suffixed");
assertThat(result).contains("suffixed"); String result = exchange.getResponse().getBodyAsString().block();
}); assertThat(result).contains("suffixed");
});
} }
@Test @Test
public void customTemplateLoaderPath() { public void customTemplateLoaderPath() {
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/").run(context -> { this.contextRunner
MockServerWebExchange exchange = render(context, "custom"); .withPropertyValues(
String result = exchange.getResponse().getBodyAsString().block(); "spring.freemarker.templateLoaderPath:classpath:/custom-templates/")
assertThat(result).contains("custom"); .run(context -> {
}); MockServerWebExchange exchange = render(context, "custom");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("custom");
});
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public void customFreeMarkerSettings() { public void customFreeMarkerSettings() {
this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") this.contextRunner
.run(context -> assertThat(context.getBean(FreeMarkerConfigurer.class).getConfiguration() .withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope")
.getSetting("boolean_format")).isEqualTo("yup,nope")); .run(context -> assertThat(context.getBean(FreeMarkerConfigurer.class)
.getConfiguration().getSetting("boolean_format"))
.isEqualTo("yup,nope"));
} }
@Test @Test
public void renderTemplate() { public void renderTemplate() {
this.contextRunner.withPropertyValues().run(context -> { this.contextRunner.withPropertyValues().run(context -> {
FreeMarkerConfigurer freemarker = context FreeMarkerConfigurer freemarker = context.getBean(FreeMarkerConfigurer.class);
.getBean(FreeMarkerConfigurer.class);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); freemarker.getConfiguration().getTemplate("message.ftl").process(this,
writer);
assertThat(writer.toString()).contains("Hello World"); assertThat(writer.toString()).contains("Hello World");
}); });
} }
@ -118,8 +125,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
} }
private MockServerWebExchange render(ApplicationContext context, String viewName) { private MockServerWebExchange render(ApplicationContext context, String viewName) {
FreeMarkerViewResolver resolver = context FreeMarkerViewResolver resolver = context.getBean(FreeMarkerViewResolver.class);
.getBean(FreeMarkerViewResolver.class);
Mono<View> view = resolver.resolveViewName(viewName, Locale.UK); Mono<View> view = resolver.resolveViewName(viewName, Locale.UK);
MockServerWebExchange exchange = MockServerWebExchange MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/path")); .from(MockServerHttpRequest.get("/path"));

View File

@ -60,9 +60,11 @@ public class FreeMarkerAutoConfigurationTests {
@Test @Test
public void nonExistentTemplateLocation() { public void nonExistentTemplateLocation() {
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" this.contextRunner
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist") .withPropertyValues("spring.freemarker.templateLoaderPath:"
.run(context -> this.output.expect(containsString("Cannot find template location"))); + "classpath:/does-not-exist/,classpath:/also-does-not-exist")
.run(context -> this.output
.expect(containsString("Cannot find template location")));
} }
@Test @Test
@ -70,15 +72,17 @@ public class FreeMarkerAutoConfigurationTests {
new File("target/test-classes/templates/empty-directory").mkdir(); new File("target/test-classes/templates/empty-directory").mkdir();
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/templates/empty-directory/").run(context -> { + "classpath:/templates/empty-directory/").run(context -> {
}); });
} }
@Test @Test
public void nonExistentLocationAndEmptyLocation() { public void nonExistentLocationAndEmptyLocation() {
new File("target/test-classes/templates/empty-directory").mkdir(); new File("target/test-classes/templates/empty-directory").mkdir();
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" this.contextRunner
+ "classpath:/does-not-exist/,classpath:/templates/empty-directory/").run(context -> { .withPropertyValues("spring.freemarker.templateLoaderPath:"
}); + "classpath:/does-not-exist/,classpath:/templates/empty-directory/")
.run(context -> {
});
} }
} }

View File

@ -90,11 +90,14 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void doubleModuleRegistration() { public void doubleModuleRegistration() {
this.contextRunner.withUserConfiguration(DoubleModulesConfig.class).withConfiguration(AutoConfigurations.of( this.contextRunner.withUserConfiguration(DoubleModulesConfig.class)
HttpMessageConvertersAutoConfiguration.class)).run(context -> { .withConfiguration(AutoConfigurations
ObjectMapper mapper = context.getBean(ObjectMapper.class); .of(HttpMessageConvertersAutoConfiguration.class))
assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); .run(context -> {
}); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.writeValueAsString(new Foo()))
.isEqualTo("{\"foo\":\"bar\"}");
});
} }
/* /*
@ -113,34 +116,42 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void customDateFormat() { public void customDateFormat() {
this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss").run(context -> { this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss")
ObjectMapper mapper = context.getBean(ObjectMapper.class); .run(context -> {
DateFormat dateFormat = mapper.getDateFormat(); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class); DateFormat dateFormat = mapper.getDateFormat();
assertThat(((SimpleDateFormat) dateFormat).toPattern()) assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class);
.isEqualTo("yyyyMMddHHmmss"); assertThat(((SimpleDateFormat) dateFormat).toPattern())
}); .isEqualTo("yyyyMMddHHmmss");
});
} }
@Test @Test
public void customJodaDateTimeFormat() throws Exception { public void customJodaDateTimeFormat() throws Exception {
this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss", this.contextRunner
"spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss").run(context -> { .withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss",
ObjectMapper mapper = context.getBean(ObjectMapper.class); "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss")
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); .run(context -> {
assertThat(mapper.writeValueAsString(dateTime)) ObjectMapper mapper = context.getBean(ObjectMapper.class);
.isEqualTo("\"1988-06-25 20:30:00\""); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30,
Date date = dateTime.toDate(); DateTimeZone.UTC);
assertThat(mapper.writeValueAsString(date)).isEqualTo("\"19880625203000\""); assertThat(mapper.writeValueAsString(dateTime))
}); .isEqualTo("\"1988-06-25 20:30:00\"");
Date date = dateTime.toDate();
assertThat(mapper.writeValueAsString(date))
.isEqualTo("\"19880625203000\"");
});
} }
@Test @Test
public void customDateFormatClass() { public void customDateFormatClass() {
this.contextRunner.withPropertyValues("spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat").run(context -> { this.contextRunner
ObjectMapper mapper = context.getBean(ObjectMapper.class); .withPropertyValues(
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat")
}); .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
});
} }
@Test @Test
@ -153,16 +164,20 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void customPropertyNamingStrategyField() { public void customPropertyNamingStrategyField() {
this.contextRunner.withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE").run(context -> { this.contextRunner
ObjectMapper mapper = context.getBean(ObjectMapper.class); .withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE")
assertThat(mapper.getPropertyNamingStrategy()) .run(context -> {
.isInstanceOf(SnakeCaseStrategy.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
}); assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class);
});
} }
@Test @Test
public void customPropertyNamingStrategyClass() { public void customPropertyNamingStrategyClass() {
this.contextRunner.withPropertyValues("spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy") this.contextRunner
.withPropertyValues(
"spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy()) assertThat(mapper.getPropertyNamingStrategy())
@ -172,123 +187,151 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void enableSerializationFeature() { public void enableSerializationFeature() {
this.contextRunner.withPropertyValues("spring.jackson.serialization.indent_output:true") this.contextRunner
.withPropertyValues("spring.jackson.serialization.indent_output:true")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault())
assertThat(mapper.getSerializationConfig() .isFalse();
.hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())) assertThat(mapper.getSerializationConfig().hasSerializationFeatures(
.isTrue(); SerializationFeature.INDENT_OUTPUT.getMask())).isTrue();
}); });
} }
@Test @Test
public void disableSerializationFeature() { public void disableSerializationFeature() {
this.contextRunner.withPropertyValues("spring.jackson.serialization.write_dates_as_timestamps:false") this.contextRunner
.withPropertyValues(
"spring.jackson.serialization.write_dates_as_timestamps:false")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()) assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
.isTrue(); .enabledByDefault()).isTrue();
assertThat(mapper.getSerializationConfig().hasSerializationFeatures( assertThat(mapper.getSerializationConfig().hasSerializationFeatures(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse(); SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask()))
.isFalse();
}); });
} }
@Test @Test
public void enableDeserializationFeature() { public void enableDeserializationFeature() {
this.contextRunner.withPropertyValues("spring.jackson.deserialization.use_big_decimal_for_floats:true") this.contextRunner
.withPropertyValues(
"spring.jackson.deserialization.use_big_decimal_for_floats:true")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()) assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS
.isFalse(); .enabledByDefault()).isFalse();
assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures( assertThat(
DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue(); mapper.getDeserializationConfig().hasDeserializationFeatures(
DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS
.getMask())).isTrue();
}); });
} }
@Test @Test
public void disableDeserializationFeature() { public void disableDeserializationFeature() {
this.contextRunner.withPropertyValues("spring.jackson.deserialization.fail-on-unknown-properties:false") this.contextRunner
.withPropertyValues(
"spring.jackson.deserialization.fail-on-unknown-properties:false")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
.isTrue(); .enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures( assertThat(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse(); mapper.getDeserializationConfig().hasDeserializationFeatures(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
.getMask())).isFalse();
}); });
} }
@Test @Test
public void enableMapperFeature() { public void enableMapperFeature() {
this.contextRunner.withPropertyValues("spring.jackson.mapper.require_setters_for_getters:true") this.contextRunner
.withPropertyValues(
"spring.jackson.mapper.require_setters_for_getters:true")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()) assertThat(
.isFalse(); MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault())
assertThat(mapper.getSerializationConfig() .isFalse();
.hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) assertThat(mapper.getSerializationConfig().hasMapperFeatures(
.isTrue(); MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask()))
assertThat(mapper.getDeserializationConfig() .isTrue();
.hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) assertThat(mapper.getDeserializationConfig().hasMapperFeatures(
.isTrue(); MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask()))
.isTrue();
}); });
} }
@Test @Test
public void disableMapperFeature() { public void disableMapperFeature() {
this.contextRunner.withPropertyValues("spring.jackson.mapper.use_annotations:false") this.contextRunner
.withPropertyValues("spring.jackson.mapper.use_annotations:false")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig() assertThat(mapper.getDeserializationConfig()
.hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse(); .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask()))
.isFalse();
assertThat(mapper.getSerializationConfig() assertThat(mapper.getSerializationConfig()
.hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse(); .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask()))
.isFalse();
}); });
} }
@Test @Test
public void enableParserFeature() { public void enableParserFeature() {
this.contextRunner.withPropertyValues("spring.jackson.parser.allow_single_quotes:true") this.contextRunner
.withPropertyValues("spring.jackson.parser.allow_single_quotes:true")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse(); assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault())
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)) .isFalse();
.isTrue(); assertThat(mapper.getFactory()
.isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)).isTrue();
}); });
} }
@Test @Test
public void disableParserFeature() { public void disableParserFeature() {
this.contextRunner.withPropertyValues("spring.jackson.parser.auto_close_source:false") this.contextRunner
.withPropertyValues("spring.jackson.parser.auto_close_source:false")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue(); assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault())
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)) .isTrue();
.isFalse(); assertThat(mapper.getFactory()
.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse();
}); });
} }
@Test @Test
public void enableGeneratorFeature() { public void enableGeneratorFeature() {
this.contextRunner.withPropertyValues("spring.jackson.generator.write_numbers_as_strings:true") this.contextRunner
.withPropertyValues(
"spring.jackson.generator.write_numbers_as_strings:true")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()) assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS
.isFalse(); .enabledByDefault()).isFalse();
assertThat(mapper.getFactory() assertThat(mapper.getFactory()
.isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); .isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS))
.isTrue();
}); });
} }
@Test @Test
public void disableGeneratorFeature() { public void disableGeneratorFeature() {
this.contextRunner.withPropertyValues("spring.jackson.generator.auto_close_target:false") this.contextRunner
.withPropertyValues("spring.jackson.generator.auto_close_target:false")
.run(context -> { .run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue(); assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault())
assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) .isTrue();
.isFalse(); assertThat(mapper.getFactory()
.isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET))
.isFalse();
}); });
} }
@ -306,18 +349,20 @@ public class JacksonAutoConfigurationTests {
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(mapper.getSerializationConfig() assertThat(mapper.getSerializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) assertThat(
.isTrue(); DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
.isTrue();
assertThat(mapper.getDeserializationConfig() assertThat(mapper.getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES))
.isFalse();
}); });
} }
@Test @Test
public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() {
this.contextRunner.withUserConfiguration(ModuleConfig.class).run(context -> { this.contextRunner.withUserConfiguration(ModuleConfig.class).run(context -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class)
.getBean(Jackson2ObjectMapperBuilder.class).build(); .build();
assertThat(context.getBean(CustomModule.class).getOwners()) assertThat(context.getBean(CustomModule.class).getOwners())
.contains((ObjectCodec) objectMapper); .contains((ObjectCodec) objectMapper);
assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue();
@ -328,8 +373,8 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void defaultSerializationInclusion() { public void defaultSerializationInclusion() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class)
.getBean(Jackson2ObjectMapperBuilder.class).build(); .build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion() assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion()
.getValueInclusion()).isEqualTo(JsonInclude.Include.USE_DEFAULTS); .getValueInclusion()).isEqualTo(JsonInclude.Include.USE_DEFAULTS);
}); });
@ -337,56 +382,65 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void customSerializationInclusion() { public void customSerializationInclusion() {
this.contextRunner.withPropertyValues("spring.jackson.default-property-inclusion:non_null") this.contextRunner
.withPropertyValues("spring.jackson.default-property-inclusion:non_null")
.run(context -> { .run(context -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build(); .getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion() assertThat(objectMapper.getSerializationConfig()
.getValueInclusion()).isEqualTo(JsonInclude.Include.NON_NULL); .getDefaultPropertyInclusion().getValueInclusion())
.isEqualTo(JsonInclude.Include.NON_NULL);
}); });
} }
@Test @Test
public void customTimeZoneFormattingADateTime() { public void customTimeZoneFormattingADateTime() {
this.contextRunner.withPropertyValues("spring.jackson.time-zone:America/Los_Angeles", this.contextRunner
"spring.jackson.date-format:zzzz", "spring.jackson.locale:en").run(context -> { .withPropertyValues("spring.jackson.time-zone:America/Los_Angeles",
ObjectMapper objectMapper = context "spring.jackson.date-format:zzzz", "spring.jackson.locale:en")
.getBean(Jackson2ObjectMapperBuilder.class).build(); .run(context -> {
DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); ObjectMapper objectMapper = context
assertThat(objectMapper.writeValueAsString(dateTime)) .getBean(Jackson2ObjectMapperBuilder.class).build();
.isEqualTo("\"Pacific Daylight Time\""); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC);
}); assertThat(objectMapper.writeValueAsString(dateTime))
.isEqualTo("\"Pacific Daylight Time\"");
});
} }
@Test @Test
public void customTimeZoneFormattingADate() throws JsonProcessingException { public void customTimeZoneFormattingADate() throws JsonProcessingException {
this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10",
"spring.jackson.date-format:z").run(context -> { "spring.jackson.date-format:z").run(context -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build(); .getBean(Jackson2ObjectMapperBuilder.class).build();
Date date = new Date(1436966242231L); Date date = new Date(1436966242231L);
assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); assertThat(objectMapper.writeValueAsString(date))
}); .isEqualTo("\"GMT+10:00\"");
});
} }
@Test @Test
public void customLocaleWithJodaTime() throws JsonProcessingException { public void customLocaleWithJodaTime() throws JsonProcessingException {
this.contextRunner.withPropertyValues("spring.jackson.locale:de_DE", "spring.jackson.date-format:zzzz", this.contextRunner
"spring.jackson.serialization.write-dates-with-zone-id:true").run(context -> { .withPropertyValues("spring.jackson.locale:de_DE",
ObjectMapper objectMapper = context.getBean(ObjectMapper.class); "spring.jackson.date-format:zzzz",
DateTime jodaTime = new DateTime(1478424650000L, "spring.jackson.serialization.write-dates-with-zone-id:true")
DateTimeZone.forID("Europe/Rome")); .run(context -> {
assertThat(objectMapper.writeValueAsString(jodaTime)) ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
.startsWith("\"Mitteleuropäische "); DateTime jodaTime = new DateTime(1478424650000L,
}); DateTimeZone.forID("Europe/Rome"));
assertThat(objectMapper.writeValueAsString(jodaTime))
.startsWith("\"Mitteleuropäische ");
});
} }
@Test @Test
public void additionalJacksonBuilderCustomization() { public void additionalJacksonBuilderCustomization() {
this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class).run(context -> { this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class)
ObjectMapper mapper = context.getBean(ObjectMapper.class); .run(context -> {
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
}); assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
});
} }
@Test @Test
@ -407,9 +461,9 @@ public class JacksonAutoConfigurationTests {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC);
String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter() String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter()
.withZone(DateTimeZone.UTC) .withZone(DateTimeZone.UTC).print(dateTime);
.print(dateTime); assertThat(mapper.writeValueAsString(dateTime))
assertThat(mapper.writeValueAsString(dateTime)).isEqualTo("\"" + expected + "\""); .isEqualTo("\"" + expected + "\"");
}); });
} }
@ -420,8 +474,8 @@ public class JacksonAutoConfigurationTests {
.getBean(ObjectMapper.class).getDeserializationConfig(); .getBean(ObjectMapper.class).getDeserializationConfig();
AnnotationIntrospector annotationIntrospector = deserializationConfig AnnotationIntrospector annotationIntrospector = deserializationConfig
.getAnnotationIntrospector().allIntrospectors().iterator().next(); .getAnnotationIntrospector().allIntrospectors().iterator().next();
assertThat(ReflectionTestUtils.getField(annotationIntrospector, "creatorBinding")) assertThat(ReflectionTestUtils.getField(annotationIntrospector,
.isEqualTo(expectedMode); "creatorBinding")).isEqualTo(expectedMode);
}); });
} }
@ -465,8 +519,7 @@ public class JacksonAutoConfigurationTests {
@Override @Override
public void serialize(Foo value, JsonGenerator jgen, public void serialize(Foo value, JsonGenerator jgen,
SerializerProvider provider) SerializerProvider provider) throws IOException {
throws IOException {
jgen.writeStartObject(); jgen.writeStartObject();
jgen.writeStringField("foo", "bar"); jgen.writeStringField("foo", "bar");
jgen.writeEndObject(); jgen.writeEndObject();

View File

@ -74,8 +74,8 @@ public class ResourcePropertiesTests {
@Test @Test
public void emptyCacheControl() { public void emptyCacheControl() {
CacheControl cacheControl = this.properties.getCache() CacheControl cacheControl = this.properties.getCache().getCachecontrol()
.getCachecontrol().toHttpCacheControl(); .toHttpCacheControl();
assertThat(cacheControl.getHeaderValue()).isNull(); assertThat(cacheControl.getHeaderValue()).isNull();
} }

View File

@ -160,8 +160,7 @@ public final class CommandLineInvoker {
private List<String> getLines(StringBuffer buffer) { private List<String> getLines(StringBuffer buffer) {
BufferedReader reader = new BufferedReader( BufferedReader reader = new BufferedReader(
new StringReader(buffer.toString())); new StringReader(buffer.toString()));
return reader.lines() return reader.lines().filter((line) -> !line.startsWith("Picked up "))
.filter((line) -> !line.startsWith("Picked up "))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View File

@ -50,11 +50,12 @@ public class RepositoryConfigurationFactoryTests {
public void snapshotRepositoriesDisabled() { public void snapshotRepositoriesDisabled() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic", TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic",
"disableSpringSnapshotRepos:true").applyToSystemProperties(() -> { "disableSpringSnapshotRepos:true").applyToSystemProperties(() -> {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration(); .createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local"); assertRepositoryConfiguration(repositoryConfiguration, "central",
return null; "local");
}); return null;
});
} }
@Test @Test
@ -73,27 +74,32 @@ public class RepositoryConfigurationFactoryTests {
@Test @Test
public void activeByPropertyProfileRepositories() { public void activeByPropertyProfileRepositories() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories", TestPropertyValues
"foo:bar").applyToSystemProperties(() -> { .of("user.home:src/test/resources/maven-settings/active-profile-repositories",
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory "foo:bar")
.createDefaultRepositoryConfiguration(); .applyToSystemProperties(() -> {
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
"spring-snapshot", "spring-milestone", "active-by-property"); .createDefaultRepositoryConfiguration();
return null; assertRepositoryConfiguration(repositoryConfiguration, "central",
}); "local", "spring-snapshot", "spring-milestone",
"active-by-property");
return null;
});
} }
@Test @Test
public void interpolationProfileRepositories() { public void interpolationProfileRepositories() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories", TestPropertyValues
"interpolate:true").applyToSystemProperties(() -> { .of("user.home:src/test/resources/maven-settings/active-profile-repositories",
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory "interpolate:true")
.createDefaultRepositoryConfiguration(); .applyToSystemProperties(() -> {
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
"spring-snapshot", "spring-milestone", "interpolate-releases", .createDefaultRepositoryConfiguration();
"interpolate-snapshots"); assertRepositoryConfiguration(repositoryConfiguration, "central",
return null; "local", "spring-snapshot", "spring-milestone",
}); "interpolate-releases", "interpolate-snapshots");
return null;
});
} }
private void assertRepositoryConfiguration( private void assertRepositoryConfiguration(

View File

@ -74,8 +74,10 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests {
return new SimpleLocalRepositoryManagerFactory().newInstance(session, return new SimpleLocalRepositoryManagerFactory().newInstance(session,
localRepository); localRepository);
}); });
TestPropertyValues.of("user.home:src/test/resources/maven-settings/property-interpolation", TestPropertyValues
"foo:bar").applyToSystemProperties(() -> { .of("user.home:src/test/resources/maven-settings/property-interpolation",
"foo:bar")
.applyToSystemProperties(() -> {
new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(
session, session,
SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem);
@ -89,11 +91,10 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils final DefaultRepositorySystemSession session = MavenRepositorySystemUtils
.newSession(); .newSession();
TestPropertyValues.of("user.home:" + userHome).applyToSystemProperties(() -> { TestPropertyValues.of("user.home:" + userHome).applyToSystemProperties(() -> {
new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session,
session, SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem);
SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); return null;
return null; });
});
RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", RemoteRepository repository = new RemoteRepository.Builder("my-server", "default",
"http://maven.example.com").build(); "http://maven.example.com").build();
assertMirrorSelectorConfiguration(session, repository); assertMirrorSelectorConfiguration(session, repository);

View File

@ -44,15 +44,11 @@ public class FilteredClassLoaderTests {
@Test @Test
public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception {
FilteredClassLoader classLoader = new FilteredClassLoader( try (FilteredClassLoader classLoader = new FilteredClassLoader(
FilteredClassLoaderTests.class); FilteredClassLoaderTests.class)) {
try {
this.thrown.expect(ClassNotFoundException.class); this.thrown.expect(ClassNotFoundException.class);
classLoader.loadClass(getClass().getName()); classLoader.loadClass(getClass().getName());
} }
finally {
classLoader.close();
}
} }
@Test @Test

View File

@ -64,8 +64,8 @@ public class RandomAccessDataFile implements RandomAccessData {
throw new IllegalArgumentException("File must not be null"); throw new IllegalArgumentException("File must not be null");
} }
if (!file.exists()) { if (!file.exists()) {
throw new IllegalArgumentException(String.format( throw new IllegalArgumentException(
"File %s must exist", file.getAbsolutePath())); String.format("File %s must exist", file.getAbsolutePath()));
} }
this.file = file; this.file = file;
this.filePool = new FilePool(file, concurrentReads); this.filePool = new FilePool(file, concurrentReads);

View File

@ -99,8 +99,7 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact
JettyReactiveWebServerFactory.logger JettyReactiveWebServerFactory.logger
.info("Server initialized with port: " + port); .info("Server initialized with port: " + port);
if (getSsl() != null && getSsl().isEnabled()) { if (getSsl() != null && getSsl().isEnabled()) {
new SslServerCustomizer(port, getSsl(), getSslStoreProvider(), customizeSsl(server, port);
getHttp2()).customize(server);
} }
for (JettyServerCustomizer customizer : getServerCustomizers()) { for (JettyServerCustomizer customizer : getServerCustomizers()) {
customizer.customize(server); customizer.customize(server);
@ -122,6 +121,11 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact
return connector; return connector;
} }
private void customizeSsl(Server server, int port) {
new SslServerCustomizer(port, getSsl(), getSslStoreProvider(), getHttp2())
.customize(server);
}
/** /**
* Returns a Jetty {@link ThreadPool} that should be used by the {@link Server}. * Returns a Jetty {@link ThreadPool} that should be used by the {@link Server}.
* @return a Jetty {@link ThreadPool} or {@code null} * @return a Jetty {@link ThreadPool} or {@code null}

View File

@ -153,8 +153,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor
server.setHandler(addHandlerWrappers(context)); server.setHandler(addHandlerWrappers(context));
this.logger.info("Server initialized with port: " + port); this.logger.info("Server initialized with port: " + port);
if (getSsl() != null && getSsl().isEnabled()) { if (getSsl() != null && getSsl().isEnabled()) {
new SslServerCustomizer(port, getSsl(), getSslStoreProvider(), customizeSsl(server, port);
getHttp2()).customize(server);
} }
for (JettyServerCustomizer customizer : getServerCustomizers()) { for (JettyServerCustomizer customizer : getServerCustomizers()) {
customizer.customize(server); customizer.customize(server);
@ -214,6 +213,11 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor
return handler; return handler;
} }
private void customizeSsl(Server server, int port) {
new SslServerCustomizer(port, getSsl(), getSslStoreProvider(), getHttp2())
.customize(server);
}
/** /**
* Configure the given Jetty {@link WebAppContext} for use. * Configure the given Jetty {@link WebAppContext} for use.
* @param context the context to configure * @param context the context to configure
@ -419,9 +423,9 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor
} }
/** /**
* Factory method called to create the {@link JettyWebServer}. Subclasses can * Factory method called to create the {@link JettyWebServer}. Subclasses can override
* override this method to return a different {@link JettyWebServer} or apply * this method to return a different {@link JettyWebServer} or apply additional
* additional processing to the Jetty server. * processing to the Jetty server.
* @param server the Jetty server. * @param server the Jetty server.
* @return a new {@link JettyWebServer} instance * @return a new {@link JettyWebServer} instance
*/ */

View File

@ -58,7 +58,8 @@ class SslServerCustomizer implements JettyServerCustomizer {
private final Http2 http2; private final Http2 http2;
SslServerCustomizer(int port, Ssl ssl, SslStoreProvider sslStoreProvider, Http2 http2) { SslServerCustomizer(int port, Ssl ssl, SslStoreProvider sslStoreProvider,
Http2 http2) {
this.port = port; this.port = port;
this.ssl = ssl; this.ssl = ssl;
this.sslStoreProvider = sslStoreProvider; this.sslStoreProvider = sslStoreProvider;
@ -69,61 +70,64 @@ class SslServerCustomizer implements JettyServerCustomizer {
public void customize(Server server) { public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory(); SslContextFactory sslContextFactory = new SslContextFactory();
configureSsl(sslContextFactory, this.ssl, this.sslStoreProvider); configureSsl(sslContextFactory, this.ssl, this.sslStoreProvider);
ServerConnector connector = createConnector(server, sslContextFactory, ServerConnector connector = createConnector(server, sslContextFactory, this.port);
this.port); server.setConnectors(new Connector[] { connector });
server.setConnectors(new Connector[] {connector});
} }
private ServerConnector createConnector(Server server, SslContextFactory sslContextFactory, int port) { private ServerConnector createConnector(Server server,
SslContextFactory sslContextFactory, int port) {
HttpConfiguration config = new HttpConfiguration(); HttpConfiguration config = new HttpConfiguration();
config.setSendServerVersion(false); config.setSendServerVersion(false);
config.setSecureScheme("https"); config.setSecureScheme("https");
config.setSecurePort(port); config.setSecurePort(port);
config.addCustomizer(new SecureRequestCustomizer()); config.addCustomizer(new SecureRequestCustomizer());
ServerConnector connector; ServerConnector connector = createServerConnector(server, sslContextFactory,
if (this.http2 != null && this.http2.getEnabled()) { config);
final boolean isAlpnPresent = ClassUtils
.isPresent("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory",
getClass().getClassLoader());
Assert.state(isAlpnPresent,
() -> "The 'org.eclipse.jetty:jetty-alpn-server' " +
"dependency is required for HTTP/2 support.");
final boolean isConscryptPresent = ClassUtils
.isPresent("org.conscrypt.Conscrypt", getClass().getClassLoader());
Assert.state(isConscryptPresent,
() -> "The 'org.eclipse.jetty.http2:http2-server' and Conscrypt " +
"dependencies are required for HTTP/2 support.");
connector = createHttp2Connector(server, config, sslContextFactory);
}
else {
connector = createSslConnector(server, config, sslContextFactory);
}
connector.setPort(port); connector.setPort(port);
return connector; return connector;
} }
private ServerConnector createSslConnector(Server server, HttpConfiguration config, private ServerConnector createServerConnector(Server server,
SslContextFactory sslContextFactory) { SslContextFactory sslContextFactory, HttpConfiguration config) {
if (this.http2 == null || !this.http2.isEnabled()) {
return createHttp11ServerConnector(server, config, sslContextFactory);
}
Assert.state(isAlpnPresent(), () -> "The 'org.eclipse.jetty:jetty-alpn-server' "
+ "dependency is required for HTTP/2 support.");
Assert.state(isConscryptPresent(),
() -> "The 'org.eclipse.jetty.http2:http2-server' and Conscrypt "
+ "dependencies are required for HTTP/2 support.");
return createHttp2ServerConnector(server, config, sslContextFactory);
}
private ServerConnector createHttp11ServerConnector(Server server,
HttpConfiguration config, SslContextFactory sslContextFactory) {
HttpConnectionFactory connectionFactory = new HttpConnectionFactory(config); HttpConnectionFactory connectionFactory = new HttpConnectionFactory(config);
SslConnectionFactory sslConnectionFactory = new SslConnectionFactory( SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(
sslContextFactory, HttpVersion.HTTP_1_1.asString()); sslContextFactory, HttpVersion.HTTP_1_1.asString());
ServerConnector serverConnector = new ServerConnector(server, return new ServerConnector(server, sslConnectionFactory, connectionFactory);
sslConnectionFactory, connectionFactory);
return serverConnector;
} }
private ServerConnector createHttp2Connector(Server server, HttpConfiguration config, private boolean isAlpnPresent() {
SslContextFactory sslContextFactory) { return ClassUtils.isPresent(
"org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory", null);
}
private boolean isConscryptPresent() {
return ClassUtils.isPresent("org.conscrypt.Conscrypt", null);
}
private ServerConnector createHttp2ServerConnector(Server server,
HttpConfiguration config, SslContextFactory sslContextFactory) {
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(config); HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(config);
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol("h2"); alpn.setDefaultProtocol("h2");
sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);
sslContextFactory.setProvider("Conscrypt"); sslContextFactory.setProvider("Conscrypt");
SslConnectionFactory ssl = new SslConnectionFactory( SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,
sslContextFactory, alpn.getProtocol()); alpn.getProtocol());
ServerConnector http2Connector = new ServerConnector( return new ServerConnector(server, ssl, alpn, h2,
server, ssl, alpn, h2, new HttpConnectionFactory(config)); new HttpConnectionFactory(config));
return http2Connector;
} }
/** /**

View File

@ -156,7 +156,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac
private void customizeSsl(Connector connector) { private void customizeSsl(Connector connector) {
new SslConnectorCustomizer(getSsl(), getSslStoreProvider()).customize(connector); new SslConnectorCustomizer(getSsl(), getSslStoreProvider()).customize(connector);
if (getHttp2() != null && getHttp2().getEnabled()) { if (getHttp2() != null && getHttp2().isEnabled()) {
connector.addUpgradeProtocol(new Http2Protocol()); connector.addUpgradeProtocol(new Http2Protocol());
} }
} }

View File

@ -323,7 +323,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto
private void customizeSsl(Connector connector) { private void customizeSsl(Connector connector) {
new SslConnectorCustomizer(getSsl(), getSslStoreProvider()).customize(connector); new SslConnectorCustomizer(getSsl(), getSslStoreProvider()).customize(connector);
if (getHttp2() != null && getHttp2().getEnabled()) { if (getHttp2() != null && getHttp2().isEnabled()) {
connector.addUpgradeProtocol(new Http2Protocol()); connector.addUpgradeProtocol(new Http2Protocol());
} }
} }

View File

@ -103,7 +103,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
.customize(builder); .customize(builder);
if (getHttp2() != null) { if (getHttp2() != null) {
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, builder.setServerOption(UndertowOptions.ENABLE_HTTP2,
getHttp2().getEnabled()); getHttp2().isEnabled());
} }
} }

View File

@ -248,7 +248,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac
.customize(builder); .customize(builder);
if (getHttp2() != null) { if (getHttp2() != null) {
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, builder.setServerOption(UndertowOptions.ENABLE_HTTP2,
getHttp2().getEnabled()); getHttp2().isEnabled());
} }
} }

View File

@ -29,7 +29,7 @@ public class Http2 {
*/ */
private boolean enabled = false; private boolean enabled = false;
public boolean getEnabled() { public boolean isEnabled() {
return this.enabled; return this.enabled;
} }