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

Polish

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