Commit 6e29ee45 authored by Phillip Webb's avatar Phillip Webb

Polish

parent 67402405
...@@ -78,6 +78,13 @@ public class ManagementServerProperties implements SecurityPrerequisite { ...@@ -78,6 +78,13 @@ public class ManagementServerProperties implements SecurityPrerequisite {
private final Security security = maybeCreateSecurity(); private final Security security = maybeCreateSecurity();
private Security maybeCreateSecurity() {
if (ClassUtils.isPresent(SECURITY_CHECK_CLASS, null)) {
return new Security();
}
return null;
}
/** /**
* Returns the management port or {@code null} if the * Returns the management port or {@code null} if the
* {@link ServerProperties#getPort() server port} should be used. * {@link ServerProperties#getPort() server port} should be used.
...@@ -183,11 +190,4 @@ public class ManagementServerProperties implements SecurityPrerequisite { ...@@ -183,11 +190,4 @@ public class ManagementServerProperties implements SecurityPrerequisite {
} }
private static Security maybeCreateSecurity() {
if (ClassUtils.isPresent(SECURITY_CHECK_CLASS, null)) {
return new Security();
}
return null;
}
} }
...@@ -152,8 +152,8 @@ public class ManagementWebSecurityAutoConfiguration { ...@@ -152,8 +152,8 @@ public class ManagementWebSecurityAutoConfiguration {
List<String> ignored = SpringBootWebSecurityConfiguration List<String> ignored = SpringBootWebSecurityConfiguration
.getIgnored(this.security); .getIgnored(this.security);
if (!this.management.getSecurity().isEnabled()) { if (!this.management.getSecurity().isEnabled()) {
ignored.addAll(Arrays ignored.addAll(Arrays.asList(EndpointPaths
.asList(getEndpointPaths(this.endpointHandlerMapping))); .get(this.endpointHandlerMapping)));
} }
if (ignored.contains("none")) { if (ignored.contains("none")) {
ignored.remove("none"); ignored.remove("none");
...@@ -333,44 +333,48 @@ public class ManagementWebSecurityAutoConfiguration { ...@@ -333,44 +333,48 @@ public class ManagementWebSecurityAutoConfiguration {
private String[] getPaths() { private String[] getPaths() {
EndpointHandlerMapping endpointHandlerMapping = ManagementWebSecurityConfigurerAdapter.this.endpointHandlerMapping; EndpointHandlerMapping endpointHandlerMapping = ManagementWebSecurityConfigurerAdapter.this.endpointHandlerMapping;
if (this.sensitive) { if (this.sensitive) {
return getEndpointPaths(endpointHandlerMapping); return EndpointPaths.get(endpointHandlerMapping);
} }
return getEndpointPaths(endpointHandlerMapping, false); return EndpointPaths.get(endpointHandlerMapping, false);
} }
} }
} }
private static String[] getEndpointPaths(EndpointHandlerMapping endpointHandlerMapping) { private static class EndpointPaths {
return StringUtils.mergeStringArrays(
getEndpointPaths(endpointHandlerMapping, false),
getEndpointPaths(endpointHandlerMapping, true));
}
private static String[] getEndpointPaths( public static String[] get(EndpointHandlerMapping endpointHandlerMapping) {
EndpointHandlerMapping endpointHandlerMapping, boolean secure) { String[] insecure = get(endpointHandlerMapping, false);
if (endpointHandlerMapping == null) { String[] secure = get(endpointHandlerMapping, true);
return NO_PATHS; return StringUtils.mergeStringArrays(insecure, secure);
} }
Set<? extends MvcEndpoint> endpoints = endpointHandlerMapping.getEndpoints();
Set<String> paths = new LinkedHashSet<String>(endpoints.size()); public static String[] get(EndpointHandlerMapping endpointHandlerMapping,
for (MvcEndpoint endpoint : endpoints) { boolean secure) {
if (endpoint.isSensitive() == secure) { if (endpointHandlerMapping == null) {
String path = endpointHandlerMapping.getPath(endpoint.getPath()); return NO_PATHS;
paths.add(path); }
if (!path.equals("")) { Set<? extends MvcEndpoint> endpoints = endpointHandlerMapping.getEndpoints();
// Ensure that nested paths are secured Set<String> paths = new LinkedHashSet<String>(endpoints.size());
paths.add(path + "/**"); for (MvcEndpoint endpoint : endpoints) {
// Add Spring MVC-generated additional paths if (endpoint.isSensitive() == secure) {
paths.add(path + ".*"); String path = endpointHandlerMapping.getPath(endpoint.getPath());
} paths.add(path);
else { if (!path.equals("")) {
paths.add("/"); // Ensure that nested paths are secured
paths.add(path + "/**");
// Add Spring MVC-generated additional paths
paths.add(path + ".*");
}
else {
paths.add("/");
}
} }
} }
return paths.toArray(new String[paths.size()]);
} }
return paths.toArray(new String[paths.size()]);
} }
} }
...@@ -105,7 +105,7 @@ public class MetricRepositoryAutoConfiguration { ...@@ -105,7 +105,7 @@ public class MetricRepositoryAutoConfiguration {
} }
@Configuration @Configuration
@ConditionalOnJava(value = JavaVersion.EIGHT) @ConditionalOnJava(JavaVersion.EIGHT)
@ConditionalOnMissingBean(GaugeService.class) @ConditionalOnMissingBean(GaugeService.class)
static class FastMetricServicesConfiguration { static class FastMetricServicesConfiguration {
......
...@@ -87,6 +87,7 @@ public class ActuatorHalBrowserEndpoint extends ActuatorHalJsonEndpoint implemen ...@@ -87,6 +87,7 @@ public class ActuatorHalBrowserEndpoint extends ActuatorHalJsonEndpoint implemen
} }
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
return null; return null;
......
...@@ -66,7 +66,7 @@ public class ActuatorHalJsonEndpoint extends WebMvcConfigurerAdapter implements ...@@ -66,7 +66,7 @@ public class ActuatorHalJsonEndpoint extends WebMvcConfigurerAdapter implements
private String getDefaultPath(ManagementServletContext managementServletContext) { private String getDefaultPath(ManagementServletContext managementServletContext) {
if (StringUtils.hasText(managementServletContext.getContextPath())) { if (StringUtils.hasText(managementServletContext.getContextPath())) {
return this.path = ""; return "";
} }
return "/actuator"; return "/actuator";
} }
......
...@@ -152,7 +152,7 @@ public class DropwizardMetricServices implements CounterService, GaugeService { ...@@ -152,7 +152,7 @@ public class DropwizardMetricServices implements CounterService, GaugeService {
/** /**
* Simple {@link Gauge} implementation to {@literal double} value. * Simple {@link Gauge} implementation to {@literal double} value.
*/ */
private static class SimpleGauge implements Gauge<Double> { private final static class SimpleGauge implements Gauge<Double> {
private final double value; private final double value;
......
...@@ -28,7 +28,10 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; ...@@ -28,7 +28,10 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
* *
* @author Luke Taylor * @author Luke Taylor
*/ */
class RedisUtils { final class RedisUtils {
private RedisUtils() {
}
static <K, V> RedisTemplate<K, V> createRedisTemplate( static <K, V> RedisTemplate<K, V> createRedisTemplate(
RedisConnectionFactory connectionFactory, Class<V> valueClass) { RedisConnectionFactory connectionFactory, Class<V> valueClass) {
......
...@@ -121,7 +121,7 @@ public class DropwizardMetricWriter implements MetricWriter { ...@@ -121,7 +121,7 @@ public class DropwizardMetricWriter implements MetricWriter {
/** /**
* Simple {@link Gauge} implementation to {@literal double} value. * Simple {@link Gauge} implementation to {@literal double} value.
*/ */
private static class SimpleGauge implements Gauge<Double> { private final static class SimpleGauge implements Gauge<Double> {
private final double value; private final double value;
......
...@@ -21,7 +21,10 @@ package org.springframework.boot.actuate.system; ...@@ -21,7 +21,10 @@ package org.springframework.boot.actuate.system;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
class SystemProperties { final class SystemProperties {
private SystemProperties() {
}
public static String get(String... properties) { public static String get(String... properties) {
for (String property : properties) { for (String property : properties) {
......
...@@ -269,18 +269,18 @@ public class PublicMetricsAutoConfigurationTests { ...@@ -269,18 +269,18 @@ public class PublicMetricsAutoConfigurationTests {
@Bean @Bean
public DataSource tomcatDataSource() { public DataSource tomcatDataSource() {
return initializeBuilder().type(org.apache.tomcat.jdbc.pool.DataSource.class) return InitalizedBuilder.create()
.build(); .type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
} }
@Bean @Bean
public DataSource hikariDS() { public DataSource hikariDS() {
return initializeBuilder().type(HikariDataSource.class).build(); return InitalizedBuilder.create().type(HikariDataSource.class).build();
} }
@Bean @Bean
public DataSource commonsDbcpDataSource() { public DataSource commonsDbcpDataSource() {
return initializeBuilder().type(BasicDataSource.class).build(); return InitalizedBuilder.create().type(BasicDataSource.class).build();
} }
} }
...@@ -290,13 +290,13 @@ public class PublicMetricsAutoConfigurationTests { ...@@ -290,13 +290,13 @@ public class PublicMetricsAutoConfigurationTests {
@Bean @Bean
@Primary @Primary
public DataSource myDataSource() { public DataSource myDataSource() {
return initializeBuilder().type(org.apache.tomcat.jdbc.pool.DataSource.class) return InitalizedBuilder.create()
.build(); .type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
} }
@Bean @Bean
public DataSource commonsDbcpDataSource() { public DataSource commonsDbcpDataSource() {
return initializeBuilder().type(BasicDataSource.class).build(); return InitalizedBuilder.create().type(BasicDataSource.class).build();
} }
} }
...@@ -306,13 +306,13 @@ public class PublicMetricsAutoConfigurationTests { ...@@ -306,13 +306,13 @@ public class PublicMetricsAutoConfigurationTests {
@Bean @Bean
@Primary @Primary
public DataSource myDataSource() { public DataSource myDataSource() {
return initializeBuilder().type(org.apache.tomcat.jdbc.pool.DataSource.class) return InitalizedBuilder.create()
.build(); .type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
} }
@Bean @Bean
public DataSource dataSource() { public DataSource dataSource() {
return initializeBuilder().type(BasicDataSource.class).build(); return InitalizedBuilder.create().type(BasicDataSource.class).build();
} }
} }
...@@ -331,11 +331,6 @@ public class PublicMetricsAutoConfigurationTests { ...@@ -331,11 +331,6 @@ public class PublicMetricsAutoConfigurationTests {
} }
} }
private static DataSourceBuilder initializeBuilder() {
return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver")
.url("jdbc:hsqldb:mem:test").username("sa");
}
@Configuration @Configuration
static class RichGaugeReaderConfig { static class RichGaugeReaderConfig {
...@@ -385,4 +380,13 @@ public class PublicMetricsAutoConfigurationTests { ...@@ -385,4 +380,13 @@ public class PublicMetricsAutoConfigurationTests {
} }
private static class InitalizedBuilder {
public static DataSourceBuilder create() {
return DataSourceBuilder.create()
.driverClassName("org.hsqldb.jdbc.JDBCDriver")
.url("jdbc:hsqldb:mem:test").username("sa");
}
}
} }
...@@ -294,18 +294,6 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ...@@ -294,18 +294,6 @@ public class ConfigurationPropertiesReportEndpointSerializationTests {
private String name = "654321"; private String name = "654321";
public static class Bar {
private String name = "123456";
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
private Bar bar = new Bar(); private Bar bar = new Bar();
public Bar getBar() { public Bar getBar() {
...@@ -329,6 +317,18 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ...@@ -329,6 +317,18 @@ public class ConfigurationPropertiesReportEndpointSerializationTests {
return "Name: " + this.name; return "Name: " + this.name;
} }
public static class Bar {
private String name = "123456";
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
} }
public static class Cycle extends Foo { public static class Cycle extends Foo {
...@@ -346,6 +346,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ...@@ -346,6 +346,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests {
public void setSelf(Foo self) { public void setSelf(Foo self) {
this.self = self; this.self = self;
} }
} }
public static class MapHolder extends Foo { public static class MapHolder extends Foo {
...@@ -359,6 +360,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ...@@ -359,6 +360,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests {
public void setMap(Map<String, Object> map) { public void setMap(Map<String, Object> map) {
this.map = map; this.map = map;
} }
} }
public static class ListHolder extends Foo { public static class ListHolder extends Foo {
...@@ -372,6 +374,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ...@@ -372,6 +374,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests {
public void setList(List<String> list) { public void setList(List<String> list) {
this.list = list; this.list = list;
} }
} }
public static class Addressed extends Foo { public static class Addressed extends Foo {
......
...@@ -46,9 +46,9 @@ public class MetricsEndpointTests extends AbstractEndpointTests<MetricsEndpoint> ...@@ -46,9 +46,9 @@ public class MetricsEndpointTests extends AbstractEndpointTests<MetricsEndpoint>
private Metric<Number> metric1 = new Metric<Number>("a", 1); private Metric<Number> metric1 = new Metric<Number>("a", 1);
private Metric<Number> metric2 = new Metric<Number>("b", 2);; private Metric<Number> metric2 = new Metric<Number>("b", 2);
private Metric<Number> metric3 = new Metric<Number>("c", 3);; private Metric<Number> metric3 = new Metric<Number>("c", 3);
public MetricsEndpointTests() { public MetricsEndpointTests() {
super(Config.class, MetricsEndpoint.class, "metrics", true, "endpoints.metrics"); super(Config.class, MetricsEndpoint.class, "metrics", true, "endpoints.metrics");
......
...@@ -170,7 +170,7 @@ public class ElasticsearchHealthIndicatorTests { ...@@ -170,7 +170,7 @@ public class ElasticsearchHealthIndicatorTests {
assertThat((T) details.get(detail), is(equalTo(value))); assertThat((T) details.get(detail), is(equalTo(value)));
} }
private static class StubClusterHealthResponse extends ClusterHealthResponse { private final static class StubClusterHealthResponse extends ClusterHealthResponse {
private final ClusterHealthStatus status; private final ClusterHealthStatus status;
......
...@@ -35,7 +35,7 @@ import static org.junit.Assert.assertEquals; ...@@ -35,7 +35,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
...@@ -72,7 +72,7 @@ public class MailHealthIndicatorTests { ...@@ -72,7 +72,7 @@ public class MailHealthIndicatorTests {
@Test @Test
public void smtpIsDown() throws MessagingException { public void smtpIsDown() throws MessagingException {
doThrow(new MessagingException("A test exception")).when(this.mailSender) willThrow(new MessagingException("A test exception")).given(this.mailSender)
.testConnection(); .testConnection();
Health health = this.indicator.health(); Health health = this.indicator.health();
assertEquals(Status.DOWN, health.getStatus()); assertEquals(Status.DOWN, health.getStatus());
......
...@@ -120,6 +120,7 @@ public class StatsdMetricWriterTests { ...@@ -120,6 +120,7 @@ public class StatsdMetricWriterTests {
.getData(), Charset.forName("UTF-8")).trim()); .getData(), Charset.forName("UTF-8")).trim());
} }
catch (Exception e) { catch (Exception e) {
// Ignore
} }
} }
}).start(); }).start();
...@@ -135,6 +136,7 @@ public class StatsdMetricWriterTests { ...@@ -135,6 +136,7 @@ public class StatsdMetricWriterTests {
Thread.sleep(50L); Thread.sleep(50L);
} }
catch (InterruptedException e) { catch (InterruptedException e) {
Thread.currentThread().interrupt();
} }
} }
} }
......
...@@ -41,9 +41,6 @@ import org.springframework.core.type.AnnotatedTypeMetadata; ...@@ -41,9 +41,6 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ConcurrentReferenceHashMap; import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static org.springframework.util.StringUtils.commaDelimitedListToStringArray;
import static org.springframework.util.StringUtils.trimAllWhitespace;
/** /**
* {@link EnableAutoConfiguration Auto-configuration} for {@link MessageSource}. * {@link EnableAutoConfiguration Auto-configuration} for {@link MessageSource}.
* *
...@@ -90,8 +87,9 @@ public class MessageSourceAutoConfiguration { ...@@ -90,8 +87,9 @@ public class MessageSourceAutoConfiguration {
public MessageSource messageSource() { public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) { if (StringUtils.hasText(this.basename)) {
messageSource messageSource.setBasenames(StringUtils
.setBasenames(commaDelimitedListToStringArray(trimAllWhitespace(this.basename))); .commaDelimitedListToStringArray(StringUtils
.trimAllWhitespace(this.basename)));
} }
if (this.encoding != null) { if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name()); messageSource.setDefaultEncoding(this.encoding.name());
...@@ -152,7 +150,8 @@ public class MessageSourceAutoConfiguration { ...@@ -152,7 +150,8 @@ public class MessageSourceAutoConfiguration {
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context,
String basename) { String basename) {
for (String name : commaDelimitedListToStringArray(trimAllWhitespace(basename))) { for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils
.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) { for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) { if (resource.exists()) {
return ConditionOutcome.match("Bundle found for " return ConditionOutcome.match("Bundle found for "
...@@ -193,6 +192,7 @@ public class MessageSourceAutoConfiguration { ...@@ -193,6 +192,7 @@ public class MessageSourceAutoConfiguration {
} }
} }
catch (Throwable ex) { catch (Throwable ex) {
// Ignore
} }
ROOT_CLASSLOADER = classLoader; ROOT_CLASSLOADER = classLoader;
} }
......
...@@ -27,7 +27,10 @@ import org.springframework.util.Assert; ...@@ -27,7 +27,10 @@ import org.springframework.util.Assert;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
class CacheConfigurations { final class CacheConfigurations {
private CacheConfigurations() {
}
private static final Map<CacheType, Class<?>> MAPPINGS; private static final Map<CacheType, Class<?>> MAPPINGS;
static { static {
......
...@@ -45,7 +45,7 @@ import org.springframework.util.ObjectUtils; ...@@ -45,7 +45,7 @@ import org.springframework.util.ObjectUtils;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ConditionEvaluationReport { public final class ConditionEvaluationReport {
private static final String BEAN_NAME = "autoConfigurationReport"; private static final String BEAN_NAME = "autoConfigurationReport";
......
...@@ -103,10 +103,11 @@ public class GroovyTemplateAutoConfiguration { ...@@ -103,10 +103,11 @@ public class GroovyTemplateAutoConfiguration {
&& codeSource.getLocation().toString().contains("-all")) { && codeSource.getLocation().toString().contains("-all")) {
return true; return true;
} }
return false;
} }
catch (Exception ex) { catch (Exception ex) {
return false;
} }
return false;
} }
@Bean @Bean
......
/* /*
* Copyright 2012-2014 the original author or authors. * Copyright 2012-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.boot.autoconfigure.groovy.template; package org.springframework.boot.autoconfigure.groovy.template;
import java.io.IOException; import java.io.IOException;
......
...@@ -43,6 +43,12 @@ import org.springframework.integration.monitor.IntegrationMBeanExporter; ...@@ -43,6 +43,12 @@ import org.springframework.integration.monitor.IntegrationMBeanExporter;
@AutoConfigureAfter(JmxAutoConfiguration.class) @AutoConfigureAfter(JmxAutoConfiguration.class)
public class IntegrationAutoConfiguration { public class IntegrationAutoConfiguration {
@Bean
@ConditionalOnMissingBean(MBeanServer.class)
public MBeanServer mbeanServer() {
return new JmxAutoConfiguration().mbeanServer();
}
@Configuration @Configuration
@EnableIntegration @EnableIntegration
protected static class IntegrationConfiguration { protected static class IntegrationConfiguration {
...@@ -56,10 +62,4 @@ public class IntegrationAutoConfiguration { ...@@ -56,10 +62,4 @@ public class IntegrationAutoConfiguration {
protected static class IntegrationJmxConfiguration { protected static class IntegrationJmxConfiguration {
} }
@Bean
@ConditionalOnMissingBean(MBeanServer.class)
public MBeanServer mbeanServer() {
return new JmxAutoConfiguration().mbeanServer();
}
} }
...@@ -39,6 +39,13 @@ import org.springframework.context.annotation.Configuration; ...@@ -39,6 +39,13 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnMissingBean(ConnectionFactory.class) @ConditionalOnMissingBean(ConnectionFactory.class)
class ActiveMQConnectionFactoryConfiguration { class ActiveMQConnectionFactoryConfiguration {
@Bean
@ConditionalOnProperty(prefix = "spring.activemq", name = "pooled", havingValue = "false", matchIfMissing = true)
public ActiveMQConnectionFactory jmsConnectionFactory(ActiveMQProperties properties) {
return new ActiveMQConnectionFactoryFactory(properties)
.createConnectionFactory(ActiveMQConnectionFactory.class);
}
@ConditionalOnClass(PooledConnectionFactory.class) @ConditionalOnClass(PooledConnectionFactory.class)
static class PooledConnectionFactoryConfiguration { static class PooledConnectionFactoryConfiguration {
...@@ -55,11 +62,4 @@ class ActiveMQConnectionFactoryConfiguration { ...@@ -55,11 +62,4 @@ class ActiveMQConnectionFactoryConfiguration {
} }
} }
@Bean
@ConditionalOnProperty(prefix = "spring.activemq", name = "pooled", havingValue = "false", matchIfMissing = true)
public ActiveMQConnectionFactory jmsConnectionFactory(ActiveMQProperties properties) {
return new ActiveMQConnectionFactoryFactory(properties)
.createConnectionFactory(ActiveMQConnectionFactory.class);
}
} }
...@@ -20,3 +20,4 @@ ...@@ -20,3 +20,4 @@
* @author Eddú Meléndez * @author Eddú Meléndez
*/ */
package org.springframework.boot.autoconfigure.jms.artemis; package org.springframework.boot.autoconfigure.jms.artemis;
...@@ -67,7 +67,7 @@ public class DeviceDelegatingViewResolverProperties { ...@@ -67,7 +67,7 @@ public class DeviceDelegatingViewResolverProperties {
} }
public boolean isEnableFallback() { public boolean isEnableFallback() {
return enableFallback; return this.enableFallback;
} }
public String getNormalPrefix() { public String getNormalPrefix() {
......
...@@ -60,8 +60,7 @@ import de.flapdoodle.embed.process.config.io.ProcessOutput; ...@@ -60,8 +60,7 @@ import de.flapdoodle.embed.process.config.io.ProcessOutput;
import de.flapdoodle.embed.process.io.Processors; import de.flapdoodle.embed.process.io.Processors;
import de.flapdoodle.embed.process.io.Slf4jLevel; import de.flapdoodle.embed.process.io.Slf4jLevel;
import de.flapdoodle.embed.process.io.progress.Slf4jProgressListener; import de.flapdoodle.embed.process.io.progress.Slf4jProgressListener;
import de.flapdoodle.embed.process.runtime.Network;
import static de.flapdoodle.embed.process.runtime.Network.localhostIsIPv6;
/** /**
* {@link EnableAutoConfiguration Auto-configuration} for Embedded Mongo. * {@link EnableAutoConfiguration Auto-configuration} for Embedded Mongo.
...@@ -139,7 +138,7 @@ public class EmbeddedMongoAutoConfiguration { ...@@ -139,7 +138,7 @@ public class EmbeddedMongoAutoConfiguration {
MongodConfigBuilder builder = new MongodConfigBuilder() MongodConfigBuilder builder = new MongodConfigBuilder()
.version(featureAwareVersion); .version(featureAwareVersion);
if (getPort() > 0) { if (getPort() > 0) {
builder.net(new Net(getPort(), localhostIsIPv6())); builder.net(new Net(getPort(), Network.localhostIsIPv6()));
} }
return builder.build(); return builder.build();
} }
...@@ -196,7 +195,7 @@ public class EmbeddedMongoAutoConfiguration { ...@@ -196,7 +195,7 @@ public class EmbeddedMongoAutoConfiguration {
* A workaround for the lack of a {@code toString} implementation on * A workaround for the lack of a {@code toString} implementation on
* {@code GenericFeatureAwareVersion}. * {@code GenericFeatureAwareVersion}.
*/ */
private static class ToStringFriendlyFeatureAwareVersion implements private final static class ToStringFriendlyFeatureAwareVersion implements
IFeatureAwareVersion { IFeatureAwareVersion {
private final String version; private final String version;
......
...@@ -80,7 +80,7 @@ public class EntityManagerFactoryBuilder { ...@@ -80,7 +80,7 @@ public class EntityManagerFactoryBuilder {
/** /**
* A fluent builder for a LocalContainerEntityManagerFactoryBean. * A fluent builder for a LocalContainerEntityManagerFactoryBean.
*/ */
public class Builder { public final class Builder {
private DataSource dataSource; private DataSource dataSource;
......
...@@ -75,6 +75,35 @@ public class OAuth2AuthorizationServerConfiguration extends ...@@ -75,6 +75,35 @@ public class OAuth2AuthorizationServerConfiguration extends
@Autowired(required = false) @Autowired(required = false)
private TokenStore tokenStore; private TokenStore tokenStore;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder builder = clients
.inMemory().withClient(this.details.getClientId());
builder.secret(this.details.getClientSecret())
.resourceIds(this.details.getResourceIds().toArray(new String[0]))
.authorizedGrantTypes(
this.details.getAuthorizedGrantTypes().toArray(new String[0]))
.authorities(
AuthorityUtils.authorityListToSet(this.details.getAuthorities())
.toArray(new String[0]))
.scopes(this.details.getScope().toArray(new String[0]));
if (this.details.getRegisteredRedirectUri() != null) {
builder.redirectUris(this.details.getRegisteredRedirectUri().toArray(
new String[0]));
}
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
if (this.tokenStore != null) {
endpoints.tokenStore(this.tokenStore);
}
if (this.details.getAuthorizedGrantTypes().contains("password")) {
endpoints.authenticationManager(this.authenticationManager);
}
}
@Configuration @Configuration
protected static class ClientDetailsLogger { protected static class ClientDetailsLogger {
...@@ -119,33 +148,4 @@ public class OAuth2AuthorizationServerConfiguration extends ...@@ -119,33 +148,4 @@ public class OAuth2AuthorizationServerConfiguration extends
} }
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder builder = clients
.inMemory().withClient(this.details.getClientId());
builder.secret(this.details.getClientSecret())
.resourceIds(this.details.getResourceIds().toArray(new String[0]))
.authorizedGrantTypes(
this.details.getAuthorizedGrantTypes().toArray(new String[0]))
.authorities(
AuthorityUtils.authorityListToSet(this.details.getAuthorities())
.toArray(new String[0]))
.scopes(this.details.getScope().toArray(new String[0]));
if (this.details.getRegisteredRedirectUri() != null) {
builder.redirectUris(this.details.getRegisteredRedirectUri().toArray(
new String[0]));
}
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
if (this.tokenStore != null) {
endpoints.tokenStore(this.tokenStore);
}
if (this.details.getAuthorizedGrantTypes().contains("password")) {
endpoints.authenticationManager(this.authenticationManager);
}
}
} }
...@@ -50,13 +50,11 @@ public class TemplateLocation { ...@@ -50,13 +50,11 @@ public class TemplateLocation {
return true; return true;
} }
try { try {
if (anyExists(resolver)) { return anyExists(resolver);
return true;
}
} }
catch (IOException ex) { catch (IOException ex) {
return false;
} }
return false;
} }
private boolean anyExists(ResourcePatternResolver resolver) throws IOException { private boolean anyExists(ResourcePatternResolver resolver) throws IOException {
......
...@@ -96,14 +96,15 @@ public class BasicErrorController implements ErrorController { ...@@ -96,14 +96,15 @@ public class BasicErrorController implements ErrorController {
protected HttpStatus getStatus(HttpServletRequest request) { protected HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code"); .getAttribute("javax.servlet.error.status_code");
if (statusCode != null) { if (statusCode == null) {
try { return HttpStatus.INTERNAL_SERVER_ERROR;
return HttpStatus.valueOf(statusCode); }
} try {
catch (Exception ex) { return HttpStatus.valueOf(statusCode);
} }
catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
} }
return HttpStatus.INTERNAL_SERVER_ERROR;
} }
} }
...@@ -122,65 +122,59 @@ public class DispatcherServletAutoConfiguration { ...@@ -122,65 +122,59 @@ public class DispatcherServletAutoConfiguration {
return checkServletRegistrations(beanFactory); return checkServletRegistrations(beanFactory);
} }
} private ConditionOutcome checkServlets(ConfigurableListableBeanFactory beanFactory) {
List<String> servlets = Arrays.asList(beanFactory.getBeanNamesForType(
private static ConditionOutcome checkServlets( DispatcherServlet.class, false, false));
ConfigurableListableBeanFactory beanFactory) { boolean containsDispatcherBean = beanFactory
List<String> servlets = Arrays.asList(beanFactory.getBeanNamesForType( .containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
DispatcherServlet.class, false, false)); if (servlets.isEmpty()) {
boolean containsDispatcherBean = beanFactory if (containsDispatcherBean) {
.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); return ConditionOutcome.noMatch("found no DispatcherServlet "
if (servlets.isEmpty()) { + "but a non-DispatcherServlet named "
+ DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
}
return ConditionOutcome.match("no DispatcherServlet found");
}
if (servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {
return ConditionOutcome.noMatch("found DispatcherServlet named "
+ DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
}
if (containsDispatcherBean) { if (containsDispatcherBean) {
return ConditionOutcome.noMatch("found no DispatcherServlet " return ConditionOutcome.noMatch("found non-DispatcherServlet named "
+ "but a non-DispatcherServlet named "
+ DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
} }
return ConditionOutcome.match("no DispatcherServlet found"); return ConditionOutcome.match("one or more DispatcherServlets "
} + "found and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
if (servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {
return ConditionOutcome.noMatch("found DispatcherServlet named "
+ DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
} }
if (containsDispatcherBean) {
return ConditionOutcome.noMatch("found non-DispatcherServlet named "
+ DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
}
return ConditionOutcome.match("one or more DispatcherServlets "
+ "found and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
}
private static ConditionOutcome checkServletRegistrations(
ConfigurableListableBeanFactory beanFactory) {
List<String> registrations = Arrays.asList(beanFactory.getBeanNamesForType( private ConditionOutcome checkServletRegistrations(
ServletRegistrationBean.class, false, false)); ConfigurableListableBeanFactory beanFactory) {
boolean containsDispatcherRegistrationBean = beanFactory List<String> registrations = Arrays.asList(beanFactory.getBeanNamesForType(
.containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); ServletRegistrationBean.class, false, false));
boolean containsDispatcherRegistrationBean = beanFactory
if (registrations.isEmpty()) { .containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
if (containsDispatcherRegistrationBean) { if (registrations.isEmpty()) {
return ConditionOutcome.noMatch("found no ServletRegistrationBean " if (containsDispatcherRegistrationBean) {
+ "but a non-ServletRegistrationBean named " return ConditionOutcome.noMatch("found no ServletRegistrationBean "
+ "but a non-ServletRegistrationBean named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
}
return ConditionOutcome.match("no ServletRegistrationBean found");
}
if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) {
return ConditionOutcome.noMatch("found ServletRegistrationBean named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
} }
return ConditionOutcome.match("no ServletRegistrationBean found"); if (containsDispatcherRegistrationBean) {
} return ConditionOutcome
.noMatch("found non-ServletRegistrationBean named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
}
return ConditionOutcome
.match("one or more ServletRegistrationBeans is found and none is named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) {
return ConditionOutcome.noMatch("found ServletRegistrationBean named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
} }
if (containsDispatcherRegistrationBean) {
return ConditionOutcome.noMatch("found non-ServletRegistrationBean named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
}
return ConditionOutcome
.match("one or more ServletRegistrationBeans is found and none is named "
+ DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
} }
} }
...@@ -75,13 +75,12 @@ import static org.hamcrest.Matchers.contains; ...@@ -75,13 +75,12 @@ import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.Is.is; import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** /**
* Tests for {@link CacheAutoConfiguration}. * Tests for {@link CacheAutoConfiguration}.
...@@ -145,7 +144,7 @@ public class CacheAutoConfigurationTests { ...@@ -145,7 +144,7 @@ public class CacheAutoConfigurationTests {
public void simpleCacheExplicit() { public void simpleCacheExplicit() {
load(DefaultCacheConfiguration.class, "spring.cache.type=simple"); load(DefaultCacheConfiguration.class, "spring.cache.type=simple");
ConcurrentMapCacheManager cacheManager = validateCacheManager(ConcurrentMapCacheManager.class); ConcurrentMapCacheManager cacheManager = validateCacheManager(ConcurrentMapCacheManager.class);
assertThat(cacheManager.getCacheNames(), is(empty())); assertThat(cacheManager.getCacheNames(), empty());
} }
@Test @Test
...@@ -191,7 +190,7 @@ public class CacheAutoConfigurationTests { ...@@ -191,7 +190,7 @@ public class CacheAutoConfigurationTests {
public void redisCacheExplicit() { public void redisCacheExplicit() {
load(RedisCacheConfiguration.class, "spring.cache.type=redis"); load(RedisCacheConfiguration.class, "spring.cache.type=redis");
RedisCacheManager cacheManager = validateCacheManager(RedisCacheManager.class); RedisCacheManager cacheManager = validateCacheManager(RedisCacheManager.class);
assertThat(cacheManager.getCacheNames(), is(empty())); assertThat(cacheManager.getCacheNames(), empty());
} }
@Test @Test
...@@ -207,7 +206,7 @@ public class CacheAutoConfigurationTests { ...@@ -207,7 +206,7 @@ public class CacheAutoConfigurationTests {
public void noOpCacheExplicit() { public void noOpCacheExplicit() {
load(DefaultCacheConfiguration.class, "spring.cache.type=none"); load(DefaultCacheConfiguration.class, "spring.cache.type=none");
NoOpCacheManager cacheManager = validateCacheManager(NoOpCacheManager.class); NoOpCacheManager cacheManager = validateCacheManager(NoOpCacheManager.class);
assertThat(cacheManager.getCacheNames(), is(empty())); assertThat(cacheManager.getCacheNames(), empty());
} }
@Test @Test
...@@ -224,9 +223,9 @@ public class CacheAutoConfigurationTests { ...@@ -224,9 +223,9 @@ public class CacheAutoConfigurationTests {
load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", load(DefaultCacheConfiguration.class, "spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn); "spring.cache.jcache.provider=" + cachingProviderFqn);
JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class);
assertThat(cacheManager.getCacheNames(), is(empty())); assertThat(cacheManager.getCacheNames(), empty());
assertThat(this.context.getBean(javax.cache.CacheManager.class), assertThat(this.context.getBean(javax.cache.CacheManager.class),
is(cacheManager.getCacheManager())); equalTo(cacheManager.getCacheManager()));
} }
@Test @Test
...@@ -263,7 +262,7 @@ public class CacheAutoConfigurationTests { ...@@ -263,7 +262,7 @@ public class CacheAutoConfigurationTests {
load(JCacheCustomCacheManager.class, "spring.cache.type=jcache"); load(JCacheCustomCacheManager.class, "spring.cache.type=jcache");
JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class);
assertThat(cacheManager.getCacheManager(), assertThat(cacheManager.getCacheManager(),
is(this.context.getBean("customJCacheCacheManager"))); equalTo(this.context.getBean("customJCacheCacheManager")));
} }
@Test @Test
...@@ -284,7 +283,8 @@ public class CacheAutoConfigurationTests { ...@@ -284,7 +283,8 @@ public class CacheAutoConfigurationTests {
"spring.cache.jcache.config=" + configLocation); "spring.cache.jcache.config=" + configLocation);
JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
assertThat(cacheManager.getCacheManager().getURI(), is(configResource.getURI())); assertThat(cacheManager.getCacheManager().getURI(),
equalTo(configResource.getURI()));
} }
@Test @Test
...@@ -307,7 +307,7 @@ public class CacheAutoConfigurationTests { ...@@ -307,7 +307,7 @@ public class CacheAutoConfigurationTests {
containsInAnyOrder("cacheTest1", "cacheTest2")); containsInAnyOrder("cacheTest1", "cacheTest2"));
assertThat(cacheManager.getCacheNames(), hasSize(2)); assertThat(cacheManager.getCacheNames(), hasSize(2));
assertThat(this.context.getBean(net.sf.ehcache.CacheManager.class), assertThat(this.context.getBean(net.sf.ehcache.CacheManager.class),
is(cacheManager.getCacheManager())); equalTo(cacheManager.getCacheManager()));
} }
@Test @Test
...@@ -325,7 +325,7 @@ public class CacheAutoConfigurationTests { ...@@ -325,7 +325,7 @@ public class CacheAutoConfigurationTests {
load(EhCacheCustomCacheManager.class, "spring.cache.type=ehcache"); load(EhCacheCustomCacheManager.class, "spring.cache.type=ehcache");
EhCacheCacheManager cacheManager = validateCacheManager(EhCacheCacheManager.class); EhCacheCacheManager cacheManager = validateCacheManager(EhCacheCacheManager.class);
assertThat(cacheManager.getCacheManager(), assertThat(cacheManager.getCacheManager(),
is(this.context.getBean("customEhCacheCacheManager"))); equalTo(this.context.getBean("customEhCacheCacheManager")));
} }
@Test @Test
...@@ -337,7 +337,7 @@ public class CacheAutoConfigurationTests { ...@@ -337,7 +337,7 @@ public class CacheAutoConfigurationTests {
assertThat(cacheManager.getCacheNames(), containsInAnyOrder("defaultCache")); assertThat(cacheManager.getCacheNames(), containsInAnyOrder("defaultCache"));
assertThat(cacheManager.getCacheNames(), hasSize(1)); assertThat(cacheManager.getCacheNames(), hasSize(1));
assertThat(this.context.getBean(HazelcastInstance.class), assertThat(this.context.getBean(HazelcastInstance.class),
is(new DirectFieldAccessor(cacheManager) equalTo(new DirectFieldAccessor(cacheManager)
.getPropertyValue("hazelcastInstance"))); .getPropertyValue("hazelcastInstance")));
} }
...@@ -367,7 +367,7 @@ public class CacheAutoConfigurationTests { ...@@ -367,7 +367,7 @@ public class CacheAutoConfigurationTests {
assertThat( assertThat(
new DirectFieldAccessor(cacheManager) new DirectFieldAccessor(cacheManager)
.getPropertyValue("hazelcastInstance"), .getPropertyValue("hazelcastInstance"),
is(this.context.getBean("customHazelcastInstance"))); equalTo(this.context.getBean("customHazelcastInstance")));
} }
@Test @Test
...@@ -384,9 +384,9 @@ public class CacheAutoConfigurationTests { ...@@ -384,9 +384,9 @@ public class CacheAutoConfigurationTests {
assertThat( assertThat(
new DirectFieldAccessor(cacheManager) new DirectFieldAccessor(cacheManager)
.getPropertyValue("hazelcastInstance"), .getPropertyValue("hazelcastInstance"),
is((Object) hazelcastInstance)); equalTo((Object) hazelcastInstance));
assertThat(hazelcastInstance.getConfig().getConfigurationFile(), assertThat(hazelcastInstance.getConfig().getConfigurationFile(),
is(new ClassPathResource(mainConfig).getFile())); equalTo(new ClassPathResource(mainConfig).getFile()));
} }
@Test @Test
...@@ -404,11 +404,11 @@ public class CacheAutoConfigurationTests { ...@@ -404,11 +404,11 @@ public class CacheAutoConfigurationTests {
HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class); HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class);
HazelcastInstance cacheHazelcastInstance = (HazelcastInstance) new DirectFieldAccessor( HazelcastInstance cacheHazelcastInstance = (HazelcastInstance) new DirectFieldAccessor(
cacheManager).getPropertyValue("hazelcastInstance"); cacheManager).getPropertyValue("hazelcastInstance");
assertThat(cacheHazelcastInstance, is(not(hazelcastInstance))); // Our custom assertThat(cacheHazelcastInstance, not(hazelcastInstance)); // Our custom
assertThat(hazelcastInstance.getConfig().getConfigurationFile(), assertThat(hazelcastInstance.getConfig().getConfigurationFile(),
is(new ClassPathResource(mainConfig).getFile())); equalTo(new ClassPathResource(mainConfig).getFile()));
assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile(), assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile(),
is(new ClassPathResource(cacheConfig).getFile())); equalTo(new ClassPathResource(cacheConfig).getFile()));
} }
@Test @Test
...@@ -432,7 +432,8 @@ public class CacheAutoConfigurationTests { ...@@ -432,7 +432,8 @@ public class CacheAutoConfigurationTests {
JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
assertThat(cacheManager.getCacheManager().getURI(), is(configResource.getURI())); assertThat(cacheManager.getCacheManager().getURI(),
equalTo(configResource.getURI()));
} }
@Test @Test
...@@ -486,7 +487,8 @@ public class CacheAutoConfigurationTests { ...@@ -486,7 +487,8 @@ public class CacheAutoConfigurationTests {
JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
assertThat(cacheManager.getCacheManager().getURI(), is(configResource.getURI())); assertThat(cacheManager.getCacheManager().getURI(),
equalTo(configResource.getURI()));
} }
@Test @Test
...@@ -538,7 +540,7 @@ public class CacheAutoConfigurationTests { ...@@ -538,7 +540,7 @@ public class CacheAutoConfigurationTests {
private <T extends CacheManager> T validateCacheManager(Class<T> type) { private <T extends CacheManager> T validateCacheManager(Class<T> type) {
CacheManager cacheManager = this.context.getBean(CacheManager.class); CacheManager cacheManager = this.context.getBean(CacheManager.class);
assertThat("Wrong cache manager type", cacheManager, is(instanceOf(type))); assertThat("Wrong cache manager type", cacheManager, instanceOf(type));
return type.cast(cacheManager); return type.cast(cacheManager);
} }
...@@ -615,8 +617,8 @@ public class CacheAutoConfigurationTests { ...@@ -615,8 +617,8 @@ public class CacheAutoConfigurationTests {
@Bean @Bean
public javax.cache.CacheManager customJCacheCacheManager() { public javax.cache.CacheManager customJCacheCacheManager() {
javax.cache.CacheManager cacheManager = mock(javax.cache.CacheManager.class); javax.cache.CacheManager cacheManager = mock(javax.cache.CacheManager.class);
when(cacheManager.getCacheNames()) given(cacheManager.getCacheNames()).willReturn(
.thenReturn(Collections.<String>emptyList()); Collections.<String>emptyList());
return cacheManager; return cacheManager;
} }
...@@ -650,8 +652,8 @@ public class CacheAutoConfigurationTests { ...@@ -650,8 +652,8 @@ public class CacheAutoConfigurationTests {
@Bean @Bean
public net.sf.ehcache.CacheManager customEhCacheCacheManager() { public net.sf.ehcache.CacheManager customEhCacheCacheManager() {
net.sf.ehcache.CacheManager cacheManager = mock(net.sf.ehcache.CacheManager.class); net.sf.ehcache.CacheManager cacheManager = mock(net.sf.ehcache.CacheManager.class);
when(cacheManager.getStatus()).thenReturn(Status.STATUS_ALIVE); given(cacheManager.getStatus()).willReturn(Status.STATUS_ALIVE);
when(cacheManager.getCacheNames()).thenReturn(new String[0]); given(cacheManager.getCacheNames()).willReturn(new String[0]);
return cacheManager; return cacheManager;
} }
...@@ -675,7 +677,7 @@ public class CacheAutoConfigurationTests { ...@@ -675,7 +677,7 @@ public class CacheAutoConfigurationTests {
@Bean @Bean
public ConfigurationBuilder configurationBuilder() { public ConfigurationBuilder configurationBuilder() {
ConfigurationBuilder builder = mock(ConfigurationBuilder.class); ConfigurationBuilder builder = mock(ConfigurationBuilder.class);
when(builder.build()).thenReturn(new ConfigurationBuilder().build()); given(builder.build()).willReturn(new ConfigurationBuilder().build());
return builder; return builder;
} }
......
...@@ -108,7 +108,7 @@ public class ConditionalOnSingleCandidateTests { ...@@ -108,7 +108,7 @@ public class ConditionalOnSingleCandidateTests {
} }
@Configuration @Configuration
@ConditionalOnSingleCandidate(value = String.class) @ConditionalOnSingleCandidate(String.class)
protected static class OnBeanSingleCandidateConfiguration { protected static class OnBeanSingleCandidateConfiguration {
@Bean @Bean
......
...@@ -25,7 +25,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext ...@@ -25,7 +25,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static org.hamcrest.core.Is.is; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
/** /**
...@@ -47,13 +47,13 @@ public class ConfigurationPropertiesAutoConfigurationTests { ...@@ -47,13 +47,13 @@ public class ConfigurationPropertiesAutoConfigurationTests {
@Test @Test
public void processAnnotatedBean() { public void processAnnotatedBean() {
load(new Class[] { AutoConfig.class, SampleBean.class }, "foo.name:test"); load(new Class[] { AutoConfig.class, SampleBean.class }, "foo.name:test");
assertThat(this.context.getBean(SampleBean.class).getName(), is("test")); assertThat(this.context.getBean(SampleBean.class).getName(), equalTo("test"));
} }
@Test @Test
public void processAnnotatedBeanNoAutoConfig() { public void processAnnotatedBeanNoAutoConfig() {
load(new Class[] { SampleBean.class }, "foo.name:test"); load(new Class[] { SampleBean.class }, "foo.name:test");
assertThat(this.context.getBean(SampleBean.class).getName(), is("default")); assertThat(this.context.getBean(SampleBean.class).getName(), equalTo("default"));
} }
private void load(Class<?>[] configs, String... environment) { private void load(Class<?>[] configs, String... environment) {
......
...@@ -32,8 +32,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext ...@@ -32,8 +32,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.repository.config.EnableSolrRepositories; import org.springframework.data.solr.repository.config.EnableSolrRepositories;
import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
/** /**
......
...@@ -52,7 +52,7 @@ public class FlywayAutoConfigurationTests { ...@@ -52,7 +52,7 @@ public class FlywayAutoConfigurationTests {
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();; private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@Before @Before
public void init() { public void init() {
......
...@@ -35,9 +35,9 @@ import com.hazelcast.config.QueueConfig; ...@@ -35,9 +35,9 @@ import com.hazelcast.config.QueueConfig;
import com.hazelcast.core.Hazelcast; import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstance;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.collection.IsMapContaining.hasKey; import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.core.Is.is; import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
/** /**
...@@ -65,7 +65,7 @@ public class HazelcastAutoConfigurationTests { ...@@ -65,7 +65,7 @@ public class HazelcastAutoConfigurationTests {
HazelcastInstance hazelcastInstance = this.context HazelcastInstance hazelcastInstance = this.context
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(hazelcastInstance.getConfig().getConfigurationUrl(), assertThat(hazelcastInstance.getConfig().getConfigurationUrl(),
is(new ClassPathResource("hazelcast.xml").getURL())); equalTo(new ClassPathResource("hazelcast.xml").getURL()));
} }
@Test @Test
...@@ -93,7 +93,7 @@ public class HazelcastAutoConfigurationTests { ...@@ -93,7 +93,7 @@ public class HazelcastAutoConfigurationTests {
HazelcastInstance hazelcastInstance = this.context HazelcastInstance hazelcastInstance = this.context
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(hazelcastInstance.getConfig().getConfigurationFile(), assertThat(hazelcastInstance.getConfig().getConfigurationFile(),
is(new ClassPathResource( equalTo(new ClassPathResource(
"org/springframework/boot/autoconfigure/hazelcast" "org/springframework/boot/autoconfigure/hazelcast"
+ "/hazelcast-specific.xml").getFile())); + "/hazelcast-specific.xml").getFile()));
} }
...@@ -104,7 +104,7 @@ public class HazelcastAutoConfigurationTests { ...@@ -104,7 +104,7 @@ public class HazelcastAutoConfigurationTests {
HazelcastInstance hazelcastInstance = this.context HazelcastInstance hazelcastInstance = this.context
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(hazelcastInstance.getConfig().getConfigurationUrl(), assertThat(hazelcastInstance.getConfig().getConfigurationUrl(),
is(new ClassPathResource("hazelcast-default.xml").getURL())); equalTo(new ClassPathResource("hazelcast-default.xml").getURL()));
} }
@Test @Test
...@@ -125,9 +125,9 @@ public class HazelcastAutoConfigurationTests { ...@@ -125,9 +125,9 @@ public class HazelcastAutoConfigurationTests {
HazelcastInstance hazelcastInstance = this.context HazelcastInstance hazelcastInstance = this.context
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(hazelcastInstance.getConfig().getInstanceName(), assertThat(hazelcastInstance.getConfig().getInstanceName(),
is("my-test-instance")); equalTo("my-test-instance"));
// Should reuse any existing instance by default. // Should reuse any existing instance by default.
assertThat(hazelcastInstance, is(existingHazelcastInstance)); assertThat(hazelcastInstance, equalTo(existingHazelcastInstance));
} }
finally { finally {
existingHazelcastInstance.shutdown(); existingHazelcastInstance.shutdown();
......
...@@ -160,13 +160,6 @@ public class JacksonAutoConfigurationTests { ...@@ -160,13 +160,6 @@ public class JacksonAutoConfigurationTests {
assertThat(mapper.getDateFormat(), is(instanceOf(MyDateFormat.class))); assertThat(mapper.getDateFormat(), is(instanceOf(MyDateFormat.class)));
} }
public static class MyDateFormat extends SimpleDateFormat {
public MyDateFormat() {
super("yyyy-MM-dd HH:mm:ss");
}
}
@Test @Test
public void noCustomPropertyNamingStrategy() throws Exception { public void noCustomPropertyNamingStrategy() throws Exception {
this.context.register(JacksonAutoConfiguration.class); this.context.register(JacksonAutoConfiguration.class);
...@@ -419,6 +412,13 @@ public class JacksonAutoConfigurationTests { ...@@ -419,6 +412,13 @@ public class JacksonAutoConfigurationTests {
objectMapper.writeValueAsString(dateTime)); objectMapper.writeValueAsString(dateTime));
} }
public static class MyDateFormat extends SimpleDateFormat {
public MyDateFormat() {
super("yyyy-MM-dd HH:mm:ss");
}
}
@Configuration @Configuration
protected static class MockObjectMapperConfig { protected static class MockObjectMapperConfig {
...@@ -469,7 +469,7 @@ public class JacksonAutoConfigurationTests { ...@@ -469,7 +469,7 @@ public class JacksonAutoConfigurationTests {
} }
protected static class Foo { protected static final class Foo {
private String name; private String name;
......
...@@ -309,7 +309,7 @@ public class ArtemisAutoConfigurationTests { ...@@ -309,7 +309,7 @@ public class ArtemisAutoConfigurationTests {
return applicationContext; return applicationContext;
} }
private static class DestinationChecker { private final static class DestinationChecker {
private final JmsTemplate jmsTemplate; private final JmsTemplate jmsTemplate;
......
...@@ -323,7 +323,7 @@ public class HornetQAutoConfigurationTests { ...@@ -323,7 +323,7 @@ public class HornetQAutoConfigurationTests {
return applicationContext; return applicationContext;
} }
private static class DestinationChecker { private final static class DestinationChecker {
private final JmsTemplate jmsTemplate; private final JmsTemplate jmsTemplate;
......
...@@ -64,7 +64,7 @@ public class TestableInitialContextFactory implements InitialContextFactory { ...@@ -64,7 +64,7 @@ public class TestableInitialContextFactory implements InitialContextFactory {
return context; return context;
} }
private static class TestableContext extends InitialContext { private final static class TestableContext extends InitialContext {
private final Map<String, Object> bindings = new HashMap<String, Object>(); private final Map<String, Object> bindings = new HashMap<String, Object>();
......
...@@ -110,6 +110,7 @@ public class JooqAutoConfigurationTests { ...@@ -110,6 +110,7 @@ public class JooqAutoConfigurationTests {
fail("An DataIntegrityViolationException should have been thrown."); fail("An DataIntegrityViolationException should have been thrown.");
} }
catch (DataIntegrityViolationException ex) { catch (DataIntegrityViolationException ex) {
// Ignore
} }
dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;",
equalTo("2"))); equalTo("2")));
...@@ -137,6 +138,7 @@ public class JooqAutoConfigurationTests { ...@@ -137,6 +138,7 @@ public class JooqAutoConfigurationTests {
fail("A DataIntegrityViolationException should have been thrown."); fail("A DataIntegrityViolationException should have been thrown.");
} }
catch (DataIntegrityViolationException ex) { catch (DataIntegrityViolationException ex) {
// Ignore
} }
dsl.transaction(new AssertFetch(dsl, dsl.transaction(new AssertFetch(dsl,
"select count(*) as total from jooqtest_tx;", equalTo("1"))); "select count(*) as total from jooqtest_tx;", equalTo("1")));
......
...@@ -24,10 +24,12 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -24,10 +24,12 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.SocketUtils;
import com.mongodb.CommandResult; import com.mongodb.CommandResult;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
...@@ -36,10 +38,7 @@ import de.flapdoodle.embed.mongo.distribution.Feature; ...@@ -36,10 +38,7 @@ import de.flapdoodle.embed.mongo.distribution.Feature;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.springframework.boot.test.EnvironmentTestUtils.addEnvironment;
import static org.springframework.util.SocketUtils.findAvailableTcpPort;
/** /**
* Tests for {@link EmbeddedMongoAutoConfiguration}. * Tests for {@link EmbeddedMongoAutoConfiguration}.
...@@ -71,9 +70,9 @@ public class EmbeddedMongoAutoConfigurationTests { ...@@ -71,9 +70,9 @@ public class EmbeddedMongoAutoConfigurationTests {
@Test @Test
public void customFeatures() { public void customFeatures() {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
int mongoPort = findAvailableTcpPort(); int mongoPort = SocketUtils.findAvailableTcpPort();
addEnvironment(this.context, "spring.data.mongodb.port=" + mongoPort, EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port="
"spring.mongodb.embedded.features=TEXT_SEARCH, SYNC_DELAY"); + mongoPort, "spring.mongodb.embedded.features=TEXT_SEARCH, SYNC_DELAY");
this.context.register(EmbeddedMongoAutoConfiguration.class); this.context.register(EmbeddedMongoAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures(), assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures(),
...@@ -83,25 +82,26 @@ public class EmbeddedMongoAutoConfigurationTests { ...@@ -83,25 +82,26 @@ public class EmbeddedMongoAutoConfigurationTests {
@Test @Test
public void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() { public void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
addEnvironment(this.context, "spring.data.mongodb.port=0"); EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port=0");
this.context.register(EmbeddedMongoAutoConfiguration.class, this.context.register(EmbeddedMongoAutoConfiguration.class,
MongoClientConfiguration.class, MongoClientConfiguration.class,
PropertyPlaceholderAutoConfiguration.class); PropertyPlaceholderAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertThat( assertThat(
this.context.getBean(MongoClient.class).getAddress().getPort(), this.context.getBean(MongoClient.class).getAddress().getPort(),
is(equalTo(Integer.valueOf(this.context.getEnvironment().getProperty( equalTo(Integer.valueOf(this.context.getEnvironment().getProperty(
"local.mongo.port"))))); "local.mongo.port"))));
} }
private void assertVersionConfiguration(String configuredVersion, private void assertVersionConfiguration(String configuredVersion,
String expectedVersion) { String expectedVersion) {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
int mongoPort = findAvailableTcpPort(); int mongoPort = SocketUtils.findAvailableTcpPort();
addEnvironment(this.context, "spring.data.mongodb.port=" + mongoPort); EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port="
+ mongoPort);
if (configuredVersion != null) { if (configuredVersion != null) {
addEnvironment(this.context, "spring.mongodb.embedded.version=" EnvironmentTestUtils.addEnvironment(this.context,
+ configuredVersion); "spring.mongodb.embedded.version=" + configuredVersion);
} }
this.context.register(MongoAutoConfiguration.class, this.context.register(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class); MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class);
......
...@@ -345,6 +345,7 @@ public class SecurityAutoConfigurationTests { ...@@ -345,6 +345,7 @@ public class SecurityAutoConfigurationTests {
fail("Expected Exception"); fail("Expected Exception");
} }
catch (AuthenticationException success) { catch (AuthenticationException success) {
// Expected
} }
token = new UsernamePasswordAuthenticationToken("foo", "bar"); token = new UsernamePasswordAuthenticationToken("foo", "bar");
......
...@@ -92,7 +92,7 @@ import org.springframework.web.client.RestTemplate; ...@@ -92,7 +92,7 @@ import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertThat;
/** /**
* Verify Spring Security OAuth2 auto-configuration secures end points properly, accepts * Verify Spring Security OAuth2 auto-configuration secures end points properly, accepts
......
...@@ -109,7 +109,7 @@ public class CustomOAuth2SsoConfigurationTests { ...@@ -109,7 +109,7 @@ public class CustomOAuth2SsoConfigurationTests {
@RestController @RestController
public static class TestController { public static class TestController {
@RequestMapping(value = "/ui/test") @RequestMapping("/ui/test")
public String test() { public String test() {
return "test"; return "test";
} }
......
...@@ -67,6 +67,7 @@ public class AbstractSocialAutoConfigurationTests { ...@@ -67,6 +67,7 @@ public class AbstractSocialAutoConfigurationTests {
fail("Unexpected bean in context of type " + beanClass.getName()); fail("Unexpected bean in context of type " + beanClass.getName());
} }
catch (NoSuchBeanDefinitionException ex) { catch (NoSuchBeanDefinitionException ex) {
// Expected
} }
} }
......
...@@ -21,8 +21,8 @@ import java.nio.charset.Charset; ...@@ -21,8 +21,8 @@ import java.nio.charset.Charset;
import org.junit.Test; import org.junit.Test;
import org.springframework.util.MimeTypeUtils; import org.springframework.util.MimeTypeUtils;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.hasToString;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link AbstractViewResolverProperties}. * Tests for {@link AbstractViewResolverProperties}.
......
...@@ -64,8 +64,8 @@ import static org.hamcrest.Matchers.is; ...@@ -64,8 +64,8 @@ import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** /**
* Tests for {@link JtaAutoConfiguration}. * Tests for {@link JtaAutoConfiguration}.
...@@ -276,10 +276,10 @@ public class JtaAutoConfigurationTests { ...@@ -276,10 +276,10 @@ public class JtaAutoConfigurationTests {
XASession session = mock(XASession.class); XASession session = mock(XASession.class);
TemporaryQueue queue = mock(TemporaryQueue.class); TemporaryQueue queue = mock(TemporaryQueue.class);
XAResource resource = mock(XAResource.class); XAResource resource = mock(XAResource.class);
when(connectionFactory.createXAConnection()).thenReturn(connection); given(connectionFactory.createXAConnection()).willReturn(connection);
when(connection.createXASession()).thenReturn(session); given(connection.createXASession()).willReturn(session);
when(session.createTemporaryQueue()).thenReturn(queue); given(session.createTemporaryQueue()).willReturn(queue);
when(session.getXAResource()).thenReturn(resource); given(session.getXAResource()).willReturn(resource);
return wrapper.wrapConnectionFactory(connectionFactory); return wrapper.wrapConnectionFactory(connectionFactory);
} }
......
...@@ -101,7 +101,7 @@ public class BasicErrorControllerDirectMockMvcTests { ...@@ -101,7 +101,7 @@ public class BasicErrorControllerDirectMockMvcTests {
WebMvcIncludedConfiguration.class).run("--server.port=0", WebMvcIncludedConfiguration.class).run("--server.port=0",
"--error.whitelabel.enabled=false")); "--error.whitelabel.enabled=false"));
thrown.expect(ServletException.class); this.thrown.expect(ServletException.class);
this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)); this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML));
} }
......
...@@ -174,7 +174,7 @@ public class BasicErrorControllerIntegrationTests { ...@@ -174,7 +174,7 @@ public class BasicErrorControllerIntegrationTests {
} }
@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@SuppressWarnings("serial") @SuppressWarnings("serial")
private static class NoReasonExpectedException extends RuntimeException { private static class NoReasonExpectedException extends RuntimeException {
......
...@@ -186,7 +186,7 @@ public class BasicErrorControllerMockMvcTests { ...@@ -186,7 +186,7 @@ public class BasicErrorControllerMockMvcTests {
} }
@ResponseStatus(value = HttpStatus.NOT_FOUND) @ResponseStatus(HttpStatus.NOT_FOUND)
private static class NotFoundException extends RuntimeException { private static class NotFoundException extends RuntimeException {
public NotFoundException(String string) { public NotFoundException(String string) {
......
...@@ -95,10 +95,6 @@ public class MultipartAutoConfigurationTests { ...@@ -95,10 +95,6 @@ public class MultipartAutoConfigurationTests {
equalTo(1)); equalTo(1));
} }
@Configuration
public static class ContainerWithNothing {
}
@Test @Test
public void containerWithNoMultipartJettyConfiguration() { public void containerWithNoMultipartJettyConfiguration() {
this.context = new AnnotationConfigEmbeddedWebApplicationContext( this.context = new AnnotationConfigEmbeddedWebApplicationContext(
...@@ -112,19 +108,6 @@ public class MultipartAutoConfigurationTests { ...@@ -112,19 +108,6 @@ public class MultipartAutoConfigurationTests {
verifyServletWorks(); verifyServletWorks();
} }
@Configuration
public static class ContainerWithNoMultipartJetty {
@Bean
JettyEmbeddedServletContainerFactory containerFactory() {
return new JettyEmbeddedServletContainerFactory();
}
@Bean
WebController controller() {
return new WebController();
}
}
@Test @Test
public void containerWithNoMultipartUndertowConfiguration() { public void containerWithNoMultipartUndertowConfiguration() {
this.context = new AnnotationConfigEmbeddedWebApplicationContext( this.context = new AnnotationConfigEmbeddedWebApplicationContext(
...@@ -138,19 +121,6 @@ public class MultipartAutoConfigurationTests { ...@@ -138,19 +121,6 @@ public class MultipartAutoConfigurationTests {
equalTo(1)); equalTo(1));
} }
@Configuration
public static class ContainerWithNoMultipartUndertow {
@Bean
UndertowEmbeddedServletContainerFactory containerFactory() {
return new UndertowEmbeddedServletContainerFactory();
}
@Bean
WebController controller() {
return new WebController();
}
}
@Test @Test
public void containerWithNoMultipartTomcatConfiguration() { public void containerWithNoMultipartTomcatConfiguration() {
this.context = new AnnotationConfigEmbeddedWebApplicationContext( this.context = new AnnotationConfigEmbeddedWebApplicationContext(
...@@ -249,6 +219,36 @@ public class MultipartAutoConfigurationTests { ...@@ -249,6 +219,36 @@ public class MultipartAutoConfigurationTests {
String.class)); String.class));
} }
@Configuration
public static class ContainerWithNothing {
}
@Configuration
public static class ContainerWithNoMultipartJetty {
@Bean
JettyEmbeddedServletContainerFactory containerFactory() {
return new JettyEmbeddedServletContainerFactory();
}
@Bean
WebController controller() {
return new WebController();
}
}
@Configuration
public static class ContainerWithNoMultipartUndertow {
@Bean
UndertowEmbeddedServletContainerFactory containerFactory() {
return new UndertowEmbeddedServletContainerFactory();
}
@Bean
WebController controller() {
return new WebController();
}
}
@Configuration @Configuration
@Import({ EmbeddedServletContainerAutoConfiguration.class, @Import({ EmbeddedServletContainerAutoConfiguration.class,
DispatcherServletAutoConfiguration.class, MultipartAutoConfiguration.class, DispatcherServletAutoConfiguration.class, MultipartAutoConfiguration.class,
......
...@@ -42,7 +42,7 @@ import org.springframework.boot.context.embedded.ServletContextInitializer; ...@@ -42,7 +42,7 @@ import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
......
...@@ -34,7 +34,10 @@ import org.springframework.boot.loader.tools.LogbackInitializer; ...@@ -34,7 +34,10 @@ import org.springframework.boot.loader.tools.LogbackInitializer;
* @see #main(String...) * @see #main(String...)
* @see CommandRunner * @see CommandRunner
*/ */
public class SpringCli { public final class SpringCli {
private SpringCli() {
}
public static void main(String... args) { public static void main(String... args) {
System.setProperty("java.awt.headless", Boolean.toString(true)); System.setProperty("java.awt.headless", Boolean.toString(true));
......
...@@ -219,6 +219,7 @@ class InitializrService { ...@@ -219,6 +219,7 @@ class InitializrService {
} }
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
return null; return null;
......
...@@ -220,7 +220,7 @@ class InitializrServiceMetadata { ...@@ -220,7 +220,7 @@ class InitializrServiceMetadata {
return result; return result;
} }
private static class MetadataHolder<K, T> { private final static class MetadataHolder<K, T> {
private final Map<K, T> content; private final Map<K, T> content;
......
...@@ -90,6 +90,7 @@ class ProjectGenerator { ...@@ -90,6 +90,7 @@ class ProjectGenerator {
return ZIP_MIME_TYPE.equals(entity.getContentType().getMimeType()); return ZIP_MIME_TYPE.equals(entity.getContentType().getMimeType());
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
return false; return false;
......
...@@ -16,9 +16,9 @@ ...@@ -16,9 +16,9 @@
package org.springframework.boot.cli.command.options; package org.springframework.boot.cli.command.options;
import joptsimple.OptionSpec; import java.util.Arrays;
import static java.util.Arrays.asList; import joptsimple.OptionSpec;
/** /**
* An {@link OptionHandler} for commands that result in the compilation of one or more * An {@link OptionHandler} for commands that result in the compilation of one or more
...@@ -46,7 +46,7 @@ public class CompilerOptionHandler extends OptionHandler { ...@@ -46,7 +46,7 @@ public class CompilerOptionHandler extends OptionHandler {
this.autoconfigureOption = option("autoconfigure", this.autoconfigureOption = option("autoconfigure",
"Add autoconfigure compiler transformations").withOptionalArg() "Add autoconfigure compiler transformations").withOptionalArg()
.ofType(Boolean.class).defaultsTo(true); .ofType(Boolean.class).defaultsTo(true);
this.classpathOption = option(asList("classpath", "cp"), this.classpathOption = option(Arrays.asList("classpath", "cp"),
"Additional classpath entries").withRequiredArg(); "Additional classpath entries").withRequiredArg();
doOptions(); doOptions();
} }
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
package org.springframework.boot.cli.command.run; package org.springframework.boot.cli.command.run;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
...@@ -33,8 +34,6 @@ import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; ...@@ -33,8 +34,6 @@ import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration;
import joptsimple.OptionSet; import joptsimple.OptionSet;
import joptsimple.OptionSpec; import joptsimple.OptionSpec;
import static java.util.Arrays.asList;
/** /**
* {@link Command} to 'run' a groovy script or scripts. * {@link Command} to 'run' a groovy script or scripts.
* *
...@@ -73,9 +72,9 @@ public class RunCommand extends OptionParsingCommand { ...@@ -73,9 +72,9 @@ public class RunCommand extends OptionParsingCommand {
@Override @Override
protected void doOptions() { protected void doOptions() {
this.watchOption = option("watch", "Watch the specified file for changes"); this.watchOption = option("watch", "Watch the specified file for changes");
this.verboseOption = option(asList("verbose", "v"), this.verboseOption = option(Arrays.asList("verbose", "v"),
"Verbose logging of dependency resolution"); "Verbose logging of dependency resolution");
this.quietOption = option(asList("quiet", "q"), "Quiet logging"); this.quietOption = option(Arrays.asList("quiet", "q"), "Quiet logging");
} }
public synchronized void stop() { public synchronized void stop() {
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
package org.springframework.boot.cli.command.run; package org.springframework.boot.cli.command.run;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
...@@ -89,22 +90,9 @@ public class SpringApplicationRunner { ...@@ -89,22 +90,9 @@ public class SpringApplicationRunner {
*/ */
public synchronized void compileAndRun() throws Exception { public synchronized void compileAndRun() throws Exception {
try { try {
stop(); stop();
Object[] compiledSources = compile();
// Compile monitorForChanges();
Object[] compiledSources = this.compiler.compile(this.sources);
if (compiledSources.length == 0) {
throw new RuntimeException("No classes found in '" + this.sources + "'");
}
// Start monitoring for changes
if (this.fileWatchThread == null
&& this.configuration.isWatchForFileChanges()) {
this.fileWatchThread = new FileWatchThread();
this.fileWatchThread.start();
}
// Run in new thread to ensure that the context classloader is setup // Run in new thread to ensure that the context classloader is setup
this.runThread = new RunThread(compiledSources); this.runThread = new RunThread(compiledSources);
this.runThread.start(); this.runThread.start();
...@@ -120,6 +108,28 @@ public class SpringApplicationRunner { ...@@ -120,6 +108,28 @@ public class SpringApplicationRunner {
} }
} }
public void stop() {
if (this.runThread != null) {
this.runThread.shutdown();
this.runThread = null;
}
}
private Object[] compile() throws IOException {
Object[] compiledSources = this.compiler.compile(this.sources);
if (compiledSources.length == 0) {
throw new RuntimeException("No classes found in '" + this.sources + "'");
}
return compiledSources;
}
private void monitorForChanges() {
if (this.fileWatchThread == null && this.configuration.isWatchForFileChanges()) {
this.fileWatchThread = new FileWatchThread();
this.fileWatchThread.start();
}
}
/** /**
* Thread used to launch the Spring Application with the correct context classloader. * Thread used to launch the Spring Application with the correct context classloader.
*/ */
...@@ -246,11 +256,4 @@ public class SpringApplicationRunner { ...@@ -246,11 +256,4 @@ public class SpringApplicationRunner {
} }
public void stop() {
if (this.runThread != null) {
this.runThread.shutdown();
this.runThread = null;
}
}
} }
...@@ -19,6 +19,7 @@ package org.springframework.boot.cli.compiler; ...@@ -19,6 +19,7 @@ package org.springframework.boot.cli.compiler;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotatedNode;
...@@ -147,32 +148,44 @@ public abstract class AstUtils { ...@@ -147,32 +148,44 @@ public abstract class AstUtils {
*/ */
public static ClosureExpression getClosure(BlockStatement block, String name, public static ClosureExpression getClosure(BlockStatement block, String name,
boolean remove) { boolean remove) {
for (ExpressionStatement statement : getExpressionStatements(block)) {
for (Statement statement : new ArrayList<Statement>(block.getStatements())) { Expression expression = statement.getExpression();
if (statement instanceof ExpressionStatement) { if (expression instanceof MethodCallExpression) {
Expression expression = ((ExpressionStatement) statement).getExpression(); ClosureExpression closure = getClosure(name,
if (expression instanceof MethodCallExpression) { (MethodCallExpression) expression);
MethodCallExpression call = (MethodCallExpression) expression; if (closure != null) {
Expression methodCall = call.getMethod(); if (remove) {
if (methodCall instanceof ConstantExpression) { block.getStatements().remove(statement);
ConstantExpression method = (ConstantExpression) methodCall;
if (name.equals(method.getValue())) {
ArgumentListExpression arguments = (ArgumentListExpression) call
.getArguments();
if (remove) {
block.getStatements().remove(statement);
}
ClosureExpression closure = (ClosureExpression) arguments
.getExpression(0);
return closure;
}
} }
return closure;
} }
} }
} }
return null; return null;
} }
private static List<ExpressionStatement> getExpressionStatements(BlockStatement block) {
ArrayList<ExpressionStatement> statements = new ArrayList<ExpressionStatement>();
for (Statement statement : block.getStatements()) {
if (statement instanceof ExpressionStatement) {
statements.add((ExpressionStatement) statement);
}
}
return statements;
}
private static ClosureExpression getClosure(String name,
MethodCallExpression expression) {
Expression method = expression.getMethod();
if (method instanceof ConstantExpression) {
if (name.equals(((ConstantExpression) method).getValue())) {
return (ClosureExpression) ((ArgumentListExpression) expression
.getArguments()).getExpression(0);
}
}
return null;
}
public static ClosureExpression getClosure(BlockStatement block, String name) { public static ClosureExpression getClosure(BlockStatement block, String name) {
return getClosure(block, name, false); return getClosure(block, name, false);
} }
......
...@@ -200,7 +200,7 @@ public class GroovyCompiler { ...@@ -200,7 +200,7 @@ public class GroovyCompiler {
for (Object loadedClass : collector.getLoadedClasses()) { for (Object loadedClass : collector.getLoadedClasses()) {
classes.add((Class<?>) loadedClass); classes.add((Class<?>) loadedClass);
} }
ClassNode mainClassNode = getMainClass(compilationUnit); ClassNode mainClassNode = MainClass.get(compilationUnit);
Class<?> mainClass = null; Class<?> mainClass = null;
for (Class<?> loadedClass : classes) { for (Class<?> loadedClass : classes) {
...@@ -275,7 +275,7 @@ public class GroovyCompiler { ...@@ -275,7 +275,7 @@ public class GroovyCompiler {
ImportCustomizer importCustomizer = new SmartImportCustomizer(source, ImportCustomizer importCustomizer = new SmartImportCustomizer(source,
context, classNode); context, classNode);
ClassNode mainClassNode = getMainClass(source.getAST().getClasses()); ClassNode mainClassNode = MainClass.get(source.getAST().getClasses());
// Additional auto configuration // Additional auto configuration
for (CompilerAutoConfiguration autoConfiguration : GroovyCompiler.this.compilerAutoConfigurations) { for (CompilerAutoConfiguration autoConfiguration : GroovyCompiler.this.compilerAutoConfigurations) {
...@@ -300,22 +300,27 @@ public class GroovyCompiler { ...@@ -300,22 +300,27 @@ public class GroovyCompiler {
} }
@SuppressWarnings("unchecked") private static class MainClass {
private static ClassNode getMainClass(CompilationUnit source) {
return getMainClass(source.getAST().getClasses());
}
private static ClassNode getMainClass(List<ClassNode> classes) { @SuppressWarnings("unchecked")
for (ClassNode node : classes) { public static ClassNode get(CompilationUnit source) {
if (AstUtils.hasAtLeastOneAnnotation(node, "Enable*AutoConfiguration")) { return get(source.getAST().getClasses());
return null; // No need to enhance this }
}
if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration", public static ClassNode get(List<ClassNode> classes) {
"Component", "*Service", "Repository", "Enable*")) { for (ClassNode node : classes) {
return node; if (AstUtils.hasAtLeastOneAnnotation(node, "Enable*AutoConfiguration")) {
return null; // No need to enhance this
}
if (AstUtils
.hasAtLeastOneAnnotation(node, "*Controller", "Configuration",
"Component", "*Service", "Repository", "Enable*")) {
return node;
}
} }
return (classes.isEmpty() ? null : classes.get(0));
} }
return (classes.isEmpty() ? null : classes.get(0));
} }
} }
...@@ -30,12 +30,15 @@ import org.springframework.boot.cli.app.SpringApplicationLauncher; ...@@ -30,12 +30,15 @@ import org.springframework.boot.cli.app.SpringApplicationLauncher;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Phillip Webb * @author Phillip Webb
*/ */
public class PackagedSpringApplicationLauncher { public final class PackagedSpringApplicationLauncher {
public static final String SOURCE_ENTRY = "Spring-Application-Source-Classes"; public static final String SOURCE_ENTRY = "Spring-Application-Source-Classes";
public static final String START_CLASS_ENTRY = "Start-Class"; public static final String START_CLASS_ENTRY = "Start-Class";
private PackagedSpringApplicationLauncher() {
}
private void run(String[] args) throws Exception { private void run(String[] args) throws Exception {
URLClassLoader classLoader = (URLClassLoader) Thread.currentThread() URLClassLoader classLoader = (URLClassLoader) Thread.currentThread()
.getContextClassLoader(); .getContextClassLoader();
......
...@@ -27,7 +27,10 @@ import org.springframework.boot.cli.command.test.TestRunner; ...@@ -27,7 +27,10 @@ import org.springframework.boot.cli.command.test.TestRunner;
* @author Phillip Webb * @author Phillip Webb
* @see TestRunner * @see TestRunner
*/ */
public class DelegateTestRunner { public final class DelegateTestRunner {
private DelegateTestRunner() {
}
public static void run(Class<?>[] testClasses, Result result) { public static void run(Class<?>[] testClasses, Result result) {
JUnitCore jUnitCore = new JUnitCore(); JUnitCore jUnitCore = new JUnitCore();
......
...@@ -24,13 +24,13 @@ import org.junit.Rule; ...@@ -24,13 +24,13 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.isA; import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** /**
* Tests for {@link InitializrService} * Tests for {@link InitializrService}
...@@ -104,7 +104,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { ...@@ -104,7 +104,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
mockSuccessfulMetadataGet(false); mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.class); CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockStatus(response, 500); mockStatus(response, 500);
when(this.http.execute(isA(HttpGet.class))).thenReturn(response); given(this.http.execute(isA(HttpGet.class))).willReturn(response);
ProjectGenerationRequest request = new ProjectGenerationRequest(); ProjectGenerationRequest request = new ProjectGenerationRequest();
this.thrown.expect(ReportableException.class); this.thrown.expect(ReportableException.class);
this.thrown.expectMessage("No content received from server"); this.thrown.expectMessage("No content received from server");
...@@ -126,7 +126,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { ...@@ -126,7 +126,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
CloseableHttpResponse response = mock(CloseableHttpResponse.class); CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, "Foo-Bar-Not-JSON".getBytes(), "application/json"); mockHttpEntity(response, "Foo-Bar-Not-JSON".getBytes(), "application/json");
mockStatus(response, 200); mockStatus(response, 200);
when(this.http.execute(isA(HttpGet.class))).thenReturn(response); given(this.http.execute(isA(HttpGet.class))).willReturn(response);
ProjectGenerationRequest request = new ProjectGenerationRequest(); ProjectGenerationRequest request = new ProjectGenerationRequest();
this.thrown.expect(ReportableException.class); this.thrown.expect(ReportableException.class);
this.thrown.expectMessage("Invalid content received from server"); this.thrown.expectMessage("Invalid content received from server");
...@@ -137,7 +137,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { ...@@ -137,7 +137,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
public void loadMetadataNoContent() throws IOException { public void loadMetadataNoContent() throws IOException {
CloseableHttpResponse response = mock(CloseableHttpResponse.class); CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockStatus(response, 500); mockStatus(response, 500);
when(this.http.execute(isA(HttpGet.class))).thenReturn(response); given(this.http.execute(isA(HttpGet.class))).willReturn(response);
ProjectGenerationRequest request = new ProjectGenerationRequest(); ProjectGenerationRequest request = new ProjectGenerationRequest();
this.thrown.expect(ReportableException.class); this.thrown.expect(ReportableException.class);
this.thrown.expectMessage("No content received from server"); this.thrown.expectMessage("No content received from server");
......
...@@ -21,7 +21,7 @@ import java.io.IOException; ...@@ -21,7 +21,7 @@ import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
/** /**
......
...@@ -25,7 +25,10 @@ import java.util.Map.Entry; ...@@ -25,7 +25,10 @@ import java.util.Map.Entry;
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class SystemProperties { public final class SystemProperties {
private SystemProperties() {
}
/** /**
* Performs the given {@code action} with the given system properties set. System * Performs the given {@code action} with the given system properties set. System
......
...@@ -35,7 +35,10 @@ import org.springframework.core.io.ClassPathResource; ...@@ -35,7 +35,10 @@ import org.springframework.core.io.ClassPathResource;
* @since 1.3.0 * @since 1.3.0
* @see RemoteClientConfiguration * @see RemoteClientConfiguration
*/ */
public class RemoteSpringApplication { public final class RemoteSpringApplication {
private RemoteSpringApplication() {
}
private void run(String[] args) { private void run(String[] args) {
Restarter.initialize(args, RestartInitializer.NONE); Restarter.initialize(args, RestartInitializer.NONE);
...@@ -60,6 +63,7 @@ public class RemoteSpringApplication { ...@@ -60,6 +63,7 @@ public class RemoteSpringApplication {
Thread.sleep(1000); Thread.sleep(1000);
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
} }
} }
......
...@@ -53,6 +53,7 @@ class FileWatchingFailureHandler implements FailureHandler { ...@@ -53,6 +53,7 @@ class FileWatchingFailureHandler implements FailureHandler {
latch.await(); latch.await();
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
return Outcome.RETRY; return Outcome.RETRY;
} }
......
...@@ -149,6 +149,7 @@ public class FileSystemWatcher { ...@@ -149,6 +149,7 @@ public class FileSystemWatcher {
scan(); scan();
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
remainingScans = FileSystemWatcher.this.remainingScans.get(); remainingScans = FileSystemWatcher.this.remainingScans.get();
} }
......
...@@ -23,7 +23,7 @@ import java.nio.charset.Charset; ...@@ -23,7 +23,7 @@ import java.nio.charset.Charset;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
class Base64Encoder { final class Base64Encoder {
private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final Charset UTF_8 = Charset.forName("UTF-8");
...@@ -34,6 +34,9 @@ class Base64Encoder { ...@@ -34,6 +34,9 @@ class Base64Encoder {
private static final byte EQUALS_SIGN = '='; private static final byte EQUALS_SIGN = '=';
private Base64Encoder() {
}
public static String encode(String string) { public static String encode(String string) {
return encode(string.getBytes(UTF_8)); return encode(string.getBytes(UTF_8));
} }
......
...@@ -95,6 +95,7 @@ class DelayedLiveReloadTrigger implements Runnable { ...@@ -95,6 +95,7 @@ class DelayedLiveReloadTrigger implements Runnable {
this.liveReloadServer.triggerReload(); this.liveReloadServer.triggerReload();
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
} }
......
...@@ -30,7 +30,7 @@ import java.util.regex.Pattern; ...@@ -30,7 +30,7 @@ import java.util.regex.Pattern;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
class ChangeableUrls implements Iterable<URL> { final class ChangeableUrls implements Iterable<URL> {
private static final String[] SKIPPED_PROJECTS = { "spring-boot", private static final String[] SKIPPED_PROJECTS = { "spring-boot",
"spring-boot-devtools", "spring-boot-autoconfigure", "spring-boot-actuator", "spring-boot-devtools", "spring-boot-autoconfigure", "spring-boot-actuator",
......
...@@ -394,6 +394,7 @@ public class Restarter { ...@@ -394,6 +394,7 @@ public class Restarter {
} }
} }
catch (final OutOfMemoryError ex) { catch (final OutOfMemoryError ex) {
// Expected
} }
} }
......
...@@ -166,6 +166,7 @@ public class HttpTunnelConnection implements TunnelConnection { ...@@ -166,6 +166,7 @@ public class HttpTunnelConnection implements TunnelConnection {
close(); close();
} }
catch (IOException ex) { catch (IOException ex) {
// Ignore
} }
} }
......
...@@ -95,6 +95,7 @@ public class TunnelClient implements SmartInitializingSingleton { ...@@ -95,6 +95,7 @@ public class TunnelClient implements SmartInitializingSingleton {
this.serverThread.join(2000); this.serverThread.join(2000);
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
this.serverThread = null; this.serverThread = null;
} }
......
...@@ -428,6 +428,7 @@ public class HttpTunnelServer { ...@@ -428,6 +428,7 @@ public class HttpTunnelServer {
} }
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
} }
} }
......
...@@ -151,6 +151,25 @@ public class LiveReloadServerTests { ...@@ -151,6 +151,25 @@ public class LiveReloadServerTests {
return socket; return socket;
} }
/**
* Useful main method for manual testing against a real browser.
* @param args main args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
LiveReloadServer server = new LiveReloadServer();
server.start();
while (true) {
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
server.triggerReload();
}
}
private static class Driver extends JettyListenerEventDriver { private static class Driver extends JettyListenerEventDriver {
private int pongCount; private int pongCount;
...@@ -197,25 +216,6 @@ public class LiveReloadServerTests { ...@@ -197,25 +216,6 @@ public class LiveReloadServerTests {
} }
/**
* Useful main method for manual testing against a real browser.
* @param args main args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
LiveReloadServer server = new LiveReloadServer();
server.start();
while (true) {
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
server.triggerReload();
}
}
/** /**
* {@link LiveReloadServer} with additional monitoring. * {@link LiveReloadServer} with additional monitoring.
*/ */
......
...@@ -228,6 +228,7 @@ public class RestarterTests { ...@@ -228,6 +228,7 @@ public class RestarterTests {
Thread.sleep(1200); Thread.sleep(1200);
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
} }
......
...@@ -124,6 +124,7 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { ...@@ -124,6 +124,7 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory {
Thread.sleep(this.delay); Thread.sleep(this.delay);
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
// Ignore
} }
} }
} }
......
...@@ -27,7 +27,10 @@ import org.xml.sax.InputSource; ...@@ -27,7 +27,10 @@ import org.xml.sax.InputSource;
/** /**
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class Versions { public final class Versions {
private Versions() {
}
public static String getBootVersion() { public static String getBootVersion() {
return evaluateExpression("/*[local-name()='project']/*[local-name()='version']" return evaluateExpression("/*[local-name()='project']/*[local-name()='version']"
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<url>http://www.spring.io</url> <url>http://www.spring.io</url>
</organization> </organization>
<properties> <properties>
<main.basedir>${basedir}/..</main.basedir> <main.basedir>${basedir}/../..</main.basedir>
</properties> </properties>
<modules> <modules>
<module>spring-boot-security-tests-web-helloworld</module> <module>spring-boot-security-tests-web-helloworld</module>
......
...@@ -32,7 +32,7 @@ import org.json.JSONException; ...@@ -32,7 +32,7 @@ import org.json.JSONException;
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 1.3.0 * @since 1.3.0
*/ */
public class ConfigurationMetadataRepositoryJsonBuilder { public final class ConfigurationMetadataRepositoryJsonBuilder {
public static final Charset UTF_8 = Charset.forName("UTF-8"); public static final Charset UTF_8 = Charset.forName("UTF-8");
......
...@@ -27,7 +27,7 @@ import javax.lang.model.element.Element; ...@@ -27,7 +27,7 @@ import javax.lang.model.element.Element;
* @author Phillip Webb * @author Phillip Webb
* @since 1.2.0 * @since 1.2.0
*/ */
class Trees extends ReflectionWrapper { final class Trees extends ReflectionWrapper {
private Trees(Object instance) { private Trees(Object instance) {
super(instance); super(instance);
......
...@@ -68,7 +68,6 @@ import static org.junit.Assert.assertTrue; ...@@ -68,7 +68,6 @@ import static org.junit.Assert.assertTrue;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup; import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsHint; import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsHint;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty; import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty;
import static org.springframework.boot.configurationprocessor.MetadataStore.METADATA_PATH;
/** /**
* Tests for {@link ConfigurationMetadataAnnotationProcessor}. * Tests for {@link ConfigurationMetadataAnnotationProcessor}.
...@@ -491,10 +490,10 @@ public class ConfigurationMetadataAnnotationProcessorTests { ...@@ -491,10 +490,10 @@ public class ConfigurationMetadataAnnotationProcessorTests {
public void incrementalBuild() throws Exception { public void incrementalBuild() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
BarProperties.class); BarProperties.class);
assertFalse(project.getOutputFile(METADATA_PATH).exists()); assertFalse(project.getOutputFile(MetadataStore.METADATA_PATH).exists());
ConfigurationMetadata metadata = project.fullBuild(); ConfigurationMetadata metadata = project.fullBuild();
assertTrue(project.getOutputFile(METADATA_PATH).exists()); assertTrue(project.getOutputFile(MetadataStore.METADATA_PATH).exists());
assertThat(metadata, assertThat(metadata,
containsProperty("foo.counter").fromSource(FooProperties.class)); containsProperty("foo.counter").fromSource(FooProperties.class));
......
...@@ -37,7 +37,10 @@ import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.Ite ...@@ -37,7 +37,10 @@ import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.Ite
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class ConfigurationMetadataMatchers { public final class ConfigurationMetadataMatchers {
private ConfigurationMetadataMatchers() {
}
public static ContainsItemMatcher containsGroup(String name) { public static ContainsItemMatcher containsGroup(String name) {
return new ContainsItemMatcher(ItemType.GROUP, name); return new ContainsItemMatcher(ItemType.GROUP, name);
......
...@@ -19,7 +19,7 @@ package org.springframework.boot.configurationprocessor.metadata; ...@@ -19,7 +19,7 @@ package org.springframework.boot.configurationprocessor.metadata;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link ConfigurationMetadata}. * Tests for {@link ConfigurationMetadata}.
......
...@@ -24,7 +24,6 @@ import org.springframework.boot.gradle.dependencymanagement.DependencyManagement ...@@ -24,7 +24,6 @@ import org.springframework.boot.gradle.dependencymanagement.DependencyManagement
import org.springframework.boot.gradle.repackage.RepackagePluginFeatures import org.springframework.boot.gradle.repackage.RepackagePluginFeatures
import org.springframework.boot.gradle.run.RunPluginFeatures import org.springframework.boot.gradle.run.RunPluginFeatures
/** /**
* Gradle 'Spring Boot' {@link Plugin}. * Gradle 'Spring Boot' {@link Plugin}.
* *
......
...@@ -18,10 +18,10 @@ package org.springframework.boot.gradle ...@@ -18,10 +18,10 @@ package org.springframework.boot.gradle
import java.io.File; import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.springframework.boot.loader.tools.Layout import org.springframework.boot.loader.tools.Layout;
import org.springframework.boot.loader.tools.Layouts import org.springframework.boot.loader.tools.Layouts;
/** /**
* Gradle DSL Extension for 'Spring Boot'. Most of the time Spring Boot can guess the * Gradle DSL Extension for 'Spring Boot'. Most of the time Spring Boot can guess the
......
...@@ -16,12 +16,12 @@ ...@@ -16,12 +16,12 @@
package org.springframework.boot.gradle.dependencymanagement; package org.springframework.boot.gradle.dependencymanagement;
import org.gradle.api.Project;
import org.springframework.boot.gradle.PluginFeatures;
import io.spring.gradle.dependencymanagement.DependencyManagementExtension import io.spring.gradle.dependencymanagement.DependencyManagementExtension
import io.spring.gradle.dependencymanagement.DependencyManagementPlugin import io.spring.gradle.dependencymanagement.DependencyManagementPlugin
import org.gradle.api.Project
import org.springframework.boot.gradle.PluginFeatures
/** /**
* {@link PluginFeatures} to configure dependency management * {@link PluginFeatures} to configure dependency management
* *
......
...@@ -28,7 +28,10 @@ import org.gradle.api.tasks.SourceSet; ...@@ -28,7 +28,10 @@ import org.gradle.api.tasks.SourceSet;
* @author Dave Syer * @author Dave Syer
* @author Phillip Webb * @author Phillip Webb
*/ */
class SourceSets { final class SourceSets {
private SourceSets() {
}
public static SourceSet findMainSourceSet(Project project) { public static SourceSet findMainSourceSet(Project project) {
for (SourceSet sourceSet : getJavaSourceSets(project)) { for (SourceSet sourceSet : getJavaSourceSets(project)) {
......
...@@ -31,7 +31,10 @@ import java.util.Set; ...@@ -31,7 +31,10 @@ import java.util.Set;
* @author Dave Syer * @author Dave Syer
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class Layouts { public final class Layouts {
private Layouts() {
}
/** /**
* Return the a layout for the given source file. * Return the a layout for the given source file.
......
...@@ -25,6 +25,9 @@ package org.springframework.boot.loader.tools; ...@@ -25,6 +25,9 @@ package org.springframework.boot.loader.tools;
*/ */
public interface LibraryScope { public interface LibraryScope {
@Override
String toString();
/** /**
* The library is used at compile time and runtime. * The library is used at compile time and runtime.
*/ */
......
...@@ -147,6 +147,7 @@ public class RunProcess { ...@@ -147,6 +147,7 @@ public class RunProcess {
reader.close(); reader.close();
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
......
...@@ -26,10 +26,13 @@ import sun.misc.SignalHandler; ...@@ -26,10 +26,13 @@ import sun.misc.SignalHandler;
* @since 1.1.0 * @since 1.1.0
*/ */
@SuppressWarnings("restriction") @SuppressWarnings("restriction")
public class SignalUtils { public final class SignalUtils {
private static final Signal SIG_INT = new Signal("INT"); private static final Signal SIG_INT = new Signal("INT");
private SignalUtils() {
}
/** /**
* Handle {@literal INT} signals by calling the specified {@link Runnable} * Handle {@literal INT} signals by calling the specified {@link Runnable}
* @param runnable the runnable to call on SIGINT. * @param runnable the runnable to call on SIGINT.
......
...@@ -23,7 +23,12 @@ package org.springframework.boot.loader.tools.sample; ...@@ -23,7 +23,12 @@ package org.springframework.boot.loader.tools.sample;
*/ */
public class ClassWithMainMethod { public class ClassWithMainMethod {
public void run() {
System.out.println("Hello World");
}
public static void main(String[] args) { public static void main(String[] args) {
new ClassWithMainMethod().run();
} }
} }
...@@ -138,6 +138,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { ...@@ -138,6 +138,7 @@ public class LaunchedURLClassLoader extends URLClassLoader {
} }
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore and continue
} }
// 2) Try to find locally // 2) Try to find locally
...@@ -147,6 +148,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { ...@@ -147,6 +148,7 @@ public class LaunchedURLClassLoader extends URLClassLoader {
return cls; return cls;
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore and continue
} }
// 3) Use standard loading // 3) Use standard loading
......
...@@ -27,10 +27,13 @@ import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess; ...@@ -27,10 +27,13 @@ import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
class Bytes { final class Bytes {
private static final byte[] EMPTY_BYTES = new byte[] {}; private static final byte[] EMPTY_BYTES = new byte[] {};
private Bytes() {
}
public static byte[] get(RandomAccessData data) throws IOException { public static byte[] get(RandomAccessData data) throws IOException {
InputStream inputStream = data.getInputStream(ResourceAccess.ONCE); InputStream inputStream = data.getInputStream(ResourceAccess.ONCE);
try { try {
......
...@@ -55,6 +55,7 @@ public class Handler extends URLStreamHandler { ...@@ -55,6 +55,7 @@ public class Handler extends URLStreamHandler {
.getDeclaredMethod("openConnection", URL.class); .getDeclaredMethod("openConnection", URL.class);
} }
catch (Exception ex) { catch (Exception ex) {
// Swallow and ignore
} }
OPEN_CONNECTION_METHOD = method; OPEN_CONNECTION_METHOD = method;
} }
......
...@@ -34,16 +34,16 @@ public class ByteArrayStartsWith extends TypeSafeMatcher<byte[]> { ...@@ -34,16 +34,16 @@ public class ByteArrayStartsWith extends TypeSafeMatcher<byte[]> {
@Override @Override
public void describeTo(Description description) { public void describeTo(Description description) {
description.appendText("a byte array starting with ").appendValue(bytes); description.appendText("a byte array starting with ").appendValue(this.bytes);
} }
@Override @Override
protected boolean matchesSafely(byte[] item) { protected boolean matchesSafely(byte[] item) {
if (item.length < bytes.length) { if (item.length < this.bytes.length) {
return false; return false;
} }
for (int i = 0; i < bytes.length; i++) { for (int i = 0; i < this.bytes.length; i++) {
if (item[i] != bytes[i]) { if (item[i] != this.bytes[i]) {
return false; return false;
} }
} }
......
...@@ -90,6 +90,17 @@ public class ExecutableArchiveLauncherTests { ...@@ -90,6 +90,17 @@ public class ExecutableArchiveLauncherTests {
assertArrayEquals(urls, ((URLClassLoader) classLoader).getURLs()); assertArrayEquals(urls, ((URLClassLoader) classLoader).getURLs());
} }
private void doWithTccl(ClassLoader classLoader, Callable<?> action) throws Exception {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
action.call();
}
finally {
Thread.currentThread().setContextClassLoader(old);
}
}
private static final class UnitTestExecutableArchiveLauncher extends private static final class UnitTestExecutableArchiveLauncher extends
ExecutableArchiveLauncher { ExecutableArchiveLauncher {
...@@ -103,15 +114,4 @@ public class ExecutableArchiveLauncherTests { ...@@ -103,15 +114,4 @@ public class ExecutableArchiveLauncherTests {
} }
} }
private void doWithTccl(ClassLoader classLoader, Callable<?> action) throws Exception {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
action.call();
}
finally {
Thread.currentThread().setContextClassLoader(old);
}
}
} }
...@@ -57,8 +57,8 @@ public class JarFileArchiveTests { ...@@ -57,8 +57,8 @@ public class JarFileArchiveTests {
private void setup(boolean unpackNested) throws Exception { private void setup(boolean unpackNested) throws Exception {
this.rootJarFile = this.temporaryFolder.newFile(); this.rootJarFile = this.temporaryFolder.newFile();
this.rootJarFileUrl = rootJarFile.toURI().toString(); this.rootJarFileUrl = this.rootJarFile.toURI().toString();
System.out.println(rootJarFileUrl); System.out.println(this.rootJarFileUrl);
TestJarCreator.createTestJar(this.rootJarFile, unpackNested); TestJarCreator.createTestJar(this.rootJarFile, unpackNested);
this.archive = new JarFileArchive(this.rootJarFile); this.archive = new JarFileArchive(this.rootJarFile);
} }
......
...@@ -72,7 +72,7 @@ public class DependencyFilterMojoTests { ...@@ -72,7 +72,7 @@ public class DependencyFilterMojoTests {
return a; return a;
} }
private static class TestableDependencyFilterMojo extends private static final class TestableDependencyFilterMojo extends
AbstractDependencyFilterMojo { AbstractDependencyFilterMojo {
private TestableDependencyFilterMojo(List<Exclude> excludes, private TestableDependencyFilterMojo(List<Exclude> excludes,
......
...@@ -40,10 +40,13 @@ import static org.junit.Assert.assertTrue; ...@@ -40,10 +40,13 @@ import static org.junit.Assert.assertTrue;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class Verify { public final class Verify {
public static final String SAMPLE_APP = "org.test.SampleApplication"; public static final String SAMPLE_APP = "org.test.SampleApplication";
private Verify() {
}
public static void verifyJar(File file) throws Exception { public static void verifyJar(File file) throws Exception {
new JarArchiveVerification(file, SAMPLE_APP).verify(); new JarArchiveVerification(file, SAMPLE_APP).verify();
} }
......
...@@ -23,7 +23,12 @@ package org.springframework.boot.maven.sample; ...@@ -23,7 +23,12 @@ package org.springframework.boot.maven.sample;
*/ */
public class ClassWithMainMethod { public class ClassWithMainMethod {
public void run() {
System.out.println("Hello World");
}
public static void main(String[] args) { public static void main(String[] args) {
new ClassWithMainMethod().run();
} }
} }
...@@ -64,10 +64,11 @@ public class ApplicationHome { ...@@ -64,10 +64,11 @@ public class ApplicationHome {
if (source != null && source.exists()) { if (source != null && source.exists()) {
return source.getAbsoluteFile(); return source.getAbsoluteFile();
} }
return null;
} }
catch (Exception ex) { catch (Exception ex) {
return null;
} }
return null;
} }
private File findSource(URL location) throws IOException { private File findSource(URL location) throws IOException {
......
...@@ -18,13 +18,11 @@ package org.springframework.boot; ...@@ -18,13 +18,11 @@ package org.springframework.boot;
import java.io.PrintStream; import java.io.PrintStream;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput; import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import static org.springframework.boot.ansi.AnsiColor.DEFAULT;
import static org.springframework.boot.ansi.AnsiColor.GREEN;
import static org.springframework.boot.ansi.AnsiStyle.FAINT;
/** /**
* Default Banner implementation which writes the 'Spring' banner. * Default Banner implementation which writes the 'Spring' banner.
* *
...@@ -58,8 +56,8 @@ class SpringBootBanner implements Banner { ...@@ -58,8 +56,8 @@ class SpringBootBanner implements Banner {
padding += " "; padding += " ";
} }
printStream.println(AnsiOutput.toString(GREEN, SPRING_BOOT, DEFAULT, padding, printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT,
FAINT, version)); AnsiColor.DEFAULT, padding, AnsiStyle.FAINT, version));
printStream.println(); printStream.println();
} }
......
...@@ -28,7 +28,10 @@ package org.springframework.boot; ...@@ -28,7 +28,10 @@ package org.springframework.boot;
* @author Drummond Dawson * @author Drummond Dawson
* @since 1.3.0 * @since 1.3.0
*/ */
public class SpringBootVersion { public final class SpringBootVersion {
private SpringBootVersion() {
}
/** /**
* Return the full version string of the present Spring Boot codebase, or {@code null} * Return the full version string of the present Spring Boot codebase, or {@code null}
......
...@@ -20,11 +20,8 @@ import java.util.Map; ...@@ -20,11 +20,8 @@ import java.util.Map;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertyResolver; import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySources;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import static java.lang.String.format;
/** /**
* {@link PropertyResolver} that attempts to resolve values using {@link RelaxedNames}. * {@link PropertyResolver} that attempts to resolve values using {@link RelaxedNames}.
* *
...@@ -56,7 +53,7 @@ public class RelaxedPropertyResolver implements PropertyResolver { ...@@ -56,7 +53,7 @@ public class RelaxedPropertyResolver implements PropertyResolver {
public <T> T getRequiredProperty(String key, Class<T> targetType) public <T> T getRequiredProperty(String key, Class<T> targetType)
throws IllegalStateException { throws IllegalStateException {
T value = getProperty(key, targetType); T value = getProperty(key, targetType);
Assert.state(value != null, format("required key [%s] not found", key)); Assert.state(value != null, String.format("required key [%s] not found", key));
return value; return value;
} }
...@@ -137,8 +134,7 @@ public class RelaxedPropertyResolver implements PropertyResolver { ...@@ -137,8 +134,7 @@ public class RelaxedPropertyResolver implements PropertyResolver {
* {@link ConfigurableEnvironment}. * {@link ConfigurableEnvironment}.
* @param keyPrefix the key prefix used to filter results * @param keyPrefix the key prefix used to filter results
* @return a map of all sub properties starting with the specified key prefix. * @return a map of all sub properties starting with the specified key prefix.
* @see PropertySourceUtils#getSubProperties(PropertySources, String) * @see PropertySourceUtils#getSubProperties
* @see PropertySourceUtils#getSubProperties(PropertySources, String, String)
*/ */
public Map<String, Object> getSubProperties(String keyPrefix) { public Map<String, Object> getSubProperties(String keyPrefix) {
Assert.isInstanceOf(ConfigurableEnvironment.class, this.resolver, Assert.isInstanceOf(ConfigurableEnvironment.class, this.resolver,
......
...@@ -96,6 +96,7 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { ...@@ -96,6 +96,7 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer {
this.server.stop(); this.server.stop();
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
......
...@@ -174,6 +174,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer ...@@ -174,6 +174,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer
this.tomcat.stop(); this.tomcat.stop();
} }
catch (LifecycleException ex) { catch (LifecycleException ex) {
// Ignore
} }
} }
......
...@@ -236,7 +236,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine ...@@ -236,7 +236,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine
/** /**
* An active undertow port. * An active undertow port.
*/ */
private static class Port { private final static class Port {
private final int number; private final int number;
......
...@@ -45,8 +45,8 @@ import org.springframework.boot.ansi.AnsiStyle; ...@@ -45,8 +45,8 @@ import org.springframework.boot.ansi.AnsiStyle;
* @since 1.3.0 * @since 1.3.0
*/ */
@Plugin(name = "color", category = PatternConverter.CATEGORY) @Plugin(name = "color", category = PatternConverter.CATEGORY)
@ConverterKeys(value = { "clr", "color" }) @ConverterKeys({ "clr", "color" })
public class ColorConverter extends LogEventPatternConverter { public final class ColorConverter extends LogEventPatternConverter {
private static final Map<String, AnsiElement> ELEMENTS; private static final Map<String, AnsiElement> ELEMENTS;
static { static {
......
...@@ -31,7 +31,7 @@ import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; ...@@ -31,7 +31,7 @@ import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter;
*/ */
@Plugin(name = "WhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY) @Plugin(name = "WhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({ "wEx", "wThrowable", "wException" }) @ConverterKeys({ "wEx", "wThrowable", "wException" })
public class WhitespaceThrowablePatternConverter extends ThrowablePatternConverter { public final class WhitespaceThrowablePatternConverter extends ThrowablePatternConverter {
private WhitespaceThrowablePatternConverter(String[] options) { private WhitespaceThrowablePatternConverter(String[] options) {
super("WhitespaceThrowable", "throwable", options); super("WhitespaceThrowable", "throwable", options);
......
...@@ -23,7 +23,7 @@ import java.nio.charset.Charset; ...@@ -23,7 +23,7 @@ import java.nio.charset.Charset;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
class Base64Encoder { final class Base64Encoder {
private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final Charset UTF_8 = Charset.forName("UTF-8");
...@@ -34,6 +34,9 @@ class Base64Encoder { ...@@ -34,6 +34,9 @@ class Base64Encoder {
private static final byte EQUALS_SIGN = '='; private static final byte EQUALS_SIGN = '=';
private Base64Encoder() {
}
public static String encode(String string) { public static String encode(String string) {
return encode(string.getBytes(UTF_8)); return encode(string.getBytes(UTF_8));
} }
......
...@@ -18,6 +18,7 @@ package org.springframework.boot.test; ...@@ -18,6 +18,7 @@ package org.springframework.boot.test;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
...@@ -147,7 +148,7 @@ public class SpringApplicationContextLoader extends AbstractContextLoader { ...@@ -147,7 +148,7 @@ public class SpringApplicationContextLoader extends AbstractContextLoader {
disableJmx(properties); disableJmx(properties);
properties.putAll(extractEnvironmentProperties(config properties.putAll(extractEnvironmentProperties(config
.getPropertySourceProperties())); .getPropertySourceProperties()));
if (!isIntegrationTest(config.getTestClass())) { if (!TestAnnotations.isIntegrationTest(config)) {
properties.putAll(getDefaultEnvironmentProperties()); properties.putAll(getDefaultEnvironmentProperties());
} }
return properties; return properties;
...@@ -252,8 +253,8 @@ public class SpringApplicationContextLoader extends AbstractContextLoader { ...@@ -252,8 +253,8 @@ public class SpringApplicationContextLoader extends AbstractContextLoader {
void configure(MergedContextConfiguration configuration, void configure(MergedContextConfiguration configuration,
SpringApplication application, SpringApplication application,
List<ApplicationContextInitializer<?>> initializers) { List<ApplicationContextInitializer<?>> initializers) {
WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration; if (!TestAnnotations.isIntegrationTest(configuration)) {
if (!isIntegrationTest(webConfiguration.getTestClass())) { WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration;
addMockServletContext(initializers, webConfiguration); addMockServletContext(initializers, webConfiguration);
application.setApplicationContextClass(WEB_CONTEXT_CLASS); application.setApplicationContextClass(WEB_CONTEXT_CLASS);
} }
...@@ -270,11 +271,6 @@ public class SpringApplicationContextLoader extends AbstractContextLoader { ...@@ -270,11 +271,6 @@ public class SpringApplicationContextLoader extends AbstractContextLoader {
} }
private static boolean isIntegrationTest(Class<?> testClass) {
return ((AnnotationUtils.findAnnotation(testClass, IntegrationTest.class) != null) || (AnnotationUtils
.findAnnotation(testClass, WebIntegrationTest.class) != null));
}
/** /**
* {@link ApplicationContextInitializer} to setup test property source locations. * {@link ApplicationContextInitializer} to setup test property source locations.
*/ */
...@@ -295,4 +291,19 @@ public class SpringApplicationContextLoader extends AbstractContextLoader { ...@@ -295,4 +291,19 @@ public class SpringApplicationContextLoader extends AbstractContextLoader {
} }
private static class TestAnnotations {
public static boolean isIntegrationTest(MergedContextConfiguration configuration) {
return (hasAnnotation(configuration, IntegrationTest.class) || hasAnnotation(
configuration, WebIntegrationTest.class));
}
private static boolean hasAnnotation(MergedContextConfiguration configuration,
Class<? extends Annotation> annotation) {
return (AnnotationUtils.findAnnotation(configuration.getTestClass(),
annotation) != null);
}
}
} }
...@@ -103,6 +103,7 @@ public class SpringBootMockServletContext extends MockServletContext { ...@@ -103,6 +103,7 @@ public class SpringBootMockServletContext extends MockServletContext {
return this.emptyRootFolder.toURI().toURL(); return this.emptyRootFolder.toURI().toURL();
} }
catch (IOException ex) { catch (IOException ex) {
// Ignore
} }
} }
return resource; return resource;
......
...@@ -23,7 +23,10 @@ import org.springframework.boot.ansi.AnsiOutput.Enabled; ...@@ -23,7 +23,10 @@ import org.springframework.boot.ansi.AnsiOutput.Enabled;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class AnsiOutputEnabledValue { public final class AnsiOutputEnabledValue {
private AnsiOutputEnabledValue() {
}
public static Enabled get() { public static Enabled get() {
return AnsiOutput.getEnabled(); return AnsiOutput.getEnabled();
......
...@@ -19,6 +19,7 @@ package org.springframework.boot.bind; ...@@ -19,6 +19,7 @@ package org.springframework.boot.bind;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
...@@ -51,7 +52,6 @@ import org.springframework.validation.DataBinder; ...@@ -51,7 +52,6 @@ import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError; import org.springframework.validation.FieldError;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
...@@ -695,7 +695,7 @@ public class RelaxedDataBinderTests { ...@@ -695,7 +695,7 @@ public class RelaxedDataBinderTests {
@Documented @Documented
@Target({ ElementType.FIELD }) @Target({ ElementType.FIELD })
@Retention(RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = RequiredKeysValidator.class) @Constraint(validatedBy = RequiredKeysValidator.class)
public @interface RequiredKeys { public @interface RequiredKeys {
......
...@@ -27,6 +27,7 @@ import java.net.URISyntaxException; ...@@ -27,6 +27,7 @@ import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.KeyStore; import java.security.KeyStore;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
...@@ -69,7 +70,6 @@ import org.springframework.util.SocketUtils; ...@@ -69,7 +70,6 @@ import org.springframework.util.SocketUtils;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFuture;
import static java.util.Collections.singletonMap;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
...@@ -110,6 +110,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { ...@@ -110,6 +110,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests {
this.container.stop(); this.container.stop();
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
} }
...@@ -584,8 +585,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { ...@@ -584,8 +585,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests {
String testContent = setUpFactoryForCompression(contentSize, mimeTypes, String testContent = setUpFactoryForCompression(contentSize, mimeTypes,
excludedUserAgents); excludedUserAgents);
TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory();
Map<String, InputStreamFactory> contentDecoderMap = singletonMap("gzip", Map<String, InputStreamFactory> contentDecoderMap = Collections.singletonMap(
(InputStreamFactory) inputStreamFactory); "gzip", (InputStreamFactory) inputStreamFactory);
String response = getResponse( String response = getResponse(
getLocalUrl("/test.txt"), getLocalUrl("/test.txt"),
new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create()
......
...@@ -61,6 +61,7 @@ public class EmbeddedServletContainerMvcIntegrationTests { ...@@ -61,6 +61,7 @@ public class EmbeddedServletContainerMvcIntegrationTests {
this.context.close(); this.context.close();
} }
catch (Exception ex) { catch (Exception ex) {
// Ignore
} }
} }
...@@ -109,6 +110,13 @@ public class EmbeddedServletContainerMvcIntegrationTests { ...@@ -109,6 +110,13 @@ public class EmbeddedServletContainerMvcIntegrationTests {
} }
} }
// Simple main method for testing in a browser
@SuppressWarnings("resource")
public static void main(String[] args) {
new AnnotationConfigEmbeddedWebApplicationContext(
JettyEmbeddedServletContainerFactory.class, Config.class);
}
@Configuration @Configuration
@Import(Config.class) @Import(Config.class)
public static class TomcatConfig { public static class TomcatConfig {
...@@ -199,13 +207,7 @@ public class EmbeddedServletContainerMvcIntegrationTests { ...@@ -199,13 +207,7 @@ public class EmbeddedServletContainerMvcIntegrationTests {
public String sayHello() { public String sayHello() {
return "Hello World"; return "Hello World";
} }
}
// Simple main method for testing in a browser
@SuppressWarnings("resource")
public static void main(String[] args) {
new AnnotationConfigEmbeddedWebApplicationContext(
JettyEmbeddedServletContainerFactory.class, Config.class);
} }
} }
...@@ -166,20 +166,6 @@ public class MockEmbeddedServletContainerFactory extends ...@@ -166,20 +166,6 @@ public class MockEmbeddedServletContainerFactory extends
return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION; return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
} }
private static class EmptyEnumeration<E> implements Enumeration<E> {
static final EmptyEnumeration<Object> EMPTY_ENUMERATION = new EmptyEnumeration<Object>();
@Override
public boolean hasMoreElements() {
return false;
}
@Override
public E nextElement() {
throw new NoSuchElementException();
}
}
@Override @Override
public void start() throws EmbeddedServletContainerException { public void start() throws EmbeddedServletContainerException {
} }
...@@ -210,6 +196,21 @@ public class MockEmbeddedServletContainerFactory extends ...@@ -210,6 +196,21 @@ public class MockEmbeddedServletContainerFactory extends
public int getPort() { public int getPort() {
return this.port; return this.port;
} }
private static class EmptyEnumeration<E> implements Enumeration<E> {
static final EmptyEnumeration<Object> EMPTY_ENUMERATION = new EmptyEnumeration<Object>();
@Override
public boolean hasMoreElements() {
return false;
}
@Override
public E nextElement() {
throw new NoSuchElementException();
}
}
} }
public static class RegisteredServlet { public static class RegisteredServlet {
......
...@@ -276,7 +276,7 @@ public class TomcatEmbeddedServletContainerFactoryTests extends ...@@ -276,7 +276,7 @@ public class TomcatEmbeddedServletContainerFactoryTests extends
fail(); fail();
} }
catch (IllegalStateException ex) { catch (IllegalStateException ex) {
// Ignore
} }
} }
...@@ -306,7 +306,7 @@ public class TomcatEmbeddedServletContainerFactoryTests extends ...@@ -306,7 +306,7 @@ public class TomcatEmbeddedServletContainerFactoryTests extends
fail(); fail();
} }
catch (IllegalStateException ex) { catch (IllegalStateException ex) {
// Ignore
} }
} }
......
...@@ -379,6 +379,17 @@ public class EnableConfigurationPropertiesTests { ...@@ -379,6 +379,17 @@ public class EnableConfigurationPropertiesTests {
assertEquals("foo", this.context.getBean(External.class).getName()); assertEquals("foo", this.context.getBean(External.class).getName());
} }
/**
* Strict tests need a known set of properties so we remove system items which may be
* environment specific.
*/
private void removeSystemProperties() {
MutablePropertySources sources = this.context.getEnvironment()
.getPropertySources();
sources.remove("systemProperties");
sources.remove("systemEnvironment");
}
@Configuration @Configuration
@EnableConfigurationProperties @EnableConfigurationProperties
public static class TestConfigurationWithAnnotatedBean { public static class TestConfigurationWithAnnotatedBean {
...@@ -391,17 +402,6 @@ public class EnableConfigurationPropertiesTests { ...@@ -391,17 +402,6 @@ public class EnableConfigurationPropertiesTests {
} }
/**
* Strict tests need a known set of properties so we remove system items which may be
* environment specific.
*/
private void removeSystemProperties() {
MutablePropertySources sources = this.context.getEnvironment()
.getPropertySources();
sources.remove("systemProperties");
sources.remove("systemEnvironment");
}
@Configuration @Configuration
@EnableConfigurationProperties(TestProperties.class) @EnableConfigurationProperties(TestProperties.class)
protected static class TestConfiguration { protected static class TestConfiguration {
......
...@@ -4,10 +4,10 @@ import org.apache.logging.log4j.core.LogEvent; ...@@ -4,10 +4,10 @@ import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link WhitespaceThrowablePatternConverter}. * Tests for {@link WhitespaceThrowablePatternConverter}.
......
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